Generate TypeScript Types from OpenAPI: Codegen Tools, Configurations, and Regeneration Workflow
TypeScriptOpenAPIAPI ClientsCode GenerationREST APIsAutomation

Generate TypeScript Types from OpenAPI: Codegen Tools, Configurations, and Regeneration Workflow

TTypeScript.page Editorial Team
2026-11-14
7 min read

Learn how to generate OpenAPI TypeScript types and clients, configure tools, review diffs, and maintain a reliable regeneration workflow.

Generating TypeScript types from an OpenAPI document can remove repetitive interface work, but only when the generated output, runtime behavior, and regeneration process are treated as one workflow. This guide compares practical code-generation approaches, shows configuration patterns for openapi-typescript and Orval, and provides a reusable checklist for reviewing changes safely whenever an API schema or toolchain changes.

Overview

OpenAPI code generation starts with a contract, usually a YAML or JSON document describing paths, parameters, request bodies, responses, authentication, and reusable schemas. A generator turns that contract into TypeScript declarations, API functions, or both. The result can improve editor completion and catch mismatches at compile time, but generated types do not automatically validate data received over the network. TypeScript disappears at runtime, so runtime validation remains a separate design decision.

The right tool depends on how much code you want generated. A types-only workflow keeps the HTTP layer under your control. A client-generation workflow can standardize request construction, response typing, error handling conventions, and framework integration. Neither approach is universally better; the important question is where your team wants the boundary between generated code and hand-written application code.

Capabilityopenapi-typescriptOrvalOther client generators
Generated modelsStrong fit for TypeScript types derived from schemasGenerates types as part of a broader client workflowVaries by generator and template
Fetch or Axios clientsUsually hand-written or paired with another toolCan generate clients for supported HTTP librariesOften a central feature
Runtime validationNot the primary purpose; add a validation layer when neededMay generate schemas or validation-oriented output depending on configurationDepends on templates and supported schema libraries
React hooksNot the primary purposeCan generate query hooks when configured for a supported data-fetching libraryDepends on the generator
Naming optionsFocused on representing the OpenAPI document in TypeScriptOffers configurable output and naming behaviorUsually template-specific
CI supportSimple command-line generation works well in CIWorks well when configuration and output are committed or checkedUsually supports CLI-based automation

Use a types-first approach when the API layer already has a stable abstraction or when you need precise control over requests. Consider a generated client when several applications repeat the same transport code, when consistency matters more than local customization, or when your team benefits from generated query hooks. Before adopting any generator, verify the OpenAPI features your specification uses, including composition, nullable values, discriminators, file uploads, security schemes, and multiple response formats.

Checklist by scenario

Scenario 1: Generate types only

  1. Choose a single canonical OpenAPI file or a reproducible schema build step.
  2. Install the generator as a project development dependency rather than relying on an untracked global installation.
  3. Define a script that writes to a clearly named generated directory.
  4. Import generated types through a small application-owned boundary instead of scattering generator-specific paths throughout the codebase.
  5. Keep request and response types distinct when the API contract distinguishes them. Avoid using a response model for a create or update payload merely because the fields look similar.
{
  "scripts": {
    "generate:api": "openapi-typescript ./openapi.yaml -o ./src/api/generated.ts",
    "typecheck": "tsc --noEmit"
  }
}

The exact command-line flags can change between tool releases, so confirm the installed version's help output and documentation when setting up or upgrading the script. Treat the script as part of the repository contract: a new developer or CI runner should be able to reproduce the same output from a clean checkout.

Scenario 2: Generate a client with Orval

Orval is useful when you want generated TypeScript types plus request functions, custom mutators, or integrations with data-fetching libraries. Keep its configuration explicit so a reader can see the input document, output directory, client style, and any hooks or transformers.

import { defineConfig } from 'orval';

export default defineConfig({
  api: {
    input: './openapi.yaml',
    output: {
      target: './src/api/generated.ts',
      client: 'fetch',
      schemas: './src/api/models',
      clean: true
    }
  }
});

If your project uses Axios, a custom request function, or a query library, configure that integration deliberately rather than accepting generated defaults without review. A custom mutator can centralize base URLs, authentication headers, serialization, and error translation, while the generated operation functions remain disposable output.

Scenario 3: Generate runtime-aware boundaries

Generated TypeScript types describe what the specification says should be present. They do not prove that a remote server, proxy, third-party integration, or outdated deployment actually returns that shape. For untrusted responses, add runtime validation at the boundary using a schema library or a hand-written assertion strategy. Keep the validated result separate from the raw transport response when that distinction helps make failures visible.

A practical boundary often looks like this:

const response = await api.getUser({ userId });
const user = UserSchema.parse(response);
return user.displayName;

The schema should be generated, maintained, or tested in a way that does not create two silently divergent sources of truth. If the OpenAPI document is authoritative, include a review step for changes that affect both generated types and runtime schemas.

What to double-check

  • Schema quality: Confirm that required fields, nullable fields, enums, formats, defaults, and read-only properties are represented accurately. A vague schema produces vague types.
  • Operation identifiers: Stable and descriptive operation IDs produce more useful function names. Renaming them can create broad generated diffs even when endpoint behavior is unchanged.
  • Composition: Review allOf, oneOf, and anyOf output. These constructs can produce unions or intersections that require explicit narrowing in application code.
  • Optional versus nullable: An optional property may be absent; a nullable property is present with a null value. Do not collapse these cases without checking the server contract.
  • Security: Check whether generated clients actually apply the required authentication scheme, and where credentials are obtained. Never place secrets in generated source or committed configuration.
  • Errors: Determine whether non-success responses are typed, thrown, returned, or left to the HTTP library. Write application code against the documented behavior, not assumptions.
  • Module boundaries: Keep generated output separate from hand-written adapters. This makes regeneration safer and supports the public API principles described in TypeScript Module Boundaries.
  • Compiler settings: Run generation and type-checking under the same project configuration used by the application. Strictness settings can expose problems that a separate, relaxed configuration hides. See the TypeScript tsconfig guide when aligning project settings.

When reviewing a generated diff, first inspect the OpenAPI change, then the generated change, and finally the application changes required to consume it. This order helps distinguish a legitimate contract change from an accidental generator or configuration change.

Common mistakes

  1. Editing generated files directly: Local fixes disappear at the next regeneration. Put customization in a wrapper, adapter, template, or supported configuration hook.
  2. Committing output without a reproducibility check: Committed generated files are useful for review and package consumers, but they should be reproducible from the declared input and tool version.
  3. Using types as runtime validation: A successful TypeScript build cannot verify a response received from a server. Add boundary validation where the risk justifies it.
  4. Generating into the application source indiscriminately: A large generated tree can obscure hand-written code and create noisy imports. Use a predictable directory and a narrow export surface.
  5. Ignoring breaking changes hidden in names: A renamed schema, operation, or enum member may compile-fail many consumers. That is valuable feedback; do not weaken types simply to make the diff smaller.
  6. Regenerating with a different tool version locally: Formatting, naming, and ordering differences can create misleading diffs. Pin the relevant dependency and use the repository's package manager consistently.

For client code used by React applications, keep generated transport functions separate from component state and presentation logic. The patterns in React TypeScript Patterns can then be applied to the hand-written layer without coupling components to generator internals.

When to revisit

Return to this checklist before a planned API release, whenever the OpenAPI document changes, and whenever a generator or its major configuration changes. It is also worth revisiting after a build failure caused by generated types, a migration from fetch to Axios, a change in query-library integration, or the introduction of runtime validation.

Use this regeneration workflow:

  1. Pull the intended OpenAPI revision and record where it came from.
  2. Install dependencies from the lockfile and run the repository's generation script.
  3. Review the generated diff for unexpected deletions, renamed operations, altered optionality, and security or error-handling changes.
  4. Run formatting, linting, and type-checking. Use the project's established test setup for request and adapter tests; the TypeScript testing setup guide provides a useful comparison of common workflows.
  5. Run focused integration tests against representative success and error responses.
  6. Commit the schema reference, configuration changes, generated output, and hand-written adaptations together when your repository tracks generated files.

Finally, reassess whether the current level of generation still fits the project. A types-only workflow may be enough for a small service, while a shared client can be worthwhile for multiple consumers. The durable goal is not maximum generated code; it is a clear, reviewable contract that keeps TypeScript, runtime behavior, and API changes aligned.

Related Topics

#TypeScript#OpenAPI#API Clients#Code Generation#REST APIs#Automation
T

TypeScript.page Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.