Skip to content

    Frontend System Design

    From OpenAPI to TypeScript Contract Types

    Learn how an OpenAPI description becomes TypeScript types for a client, what generation guarantees, what it cannot check at run time, and how to stop drift.

    By Published 12 min read

    • frontend-system-design
    • openapi
    • typescript
    • api-contracts
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: API Contracts and Data Transformation

    What you'll learn: By the end of this lesson you will be able to say what an OpenAPI description contains and which parts a client cares about, describe how types are generated from it and where they are used, list what generated types guarantee (the client matches the description) and what they do not (the server matches the description, and the bytes match the types), set up a drift check in CI, and combine generated types with the run-time edge from the previous lesson.

    An architect hands a builder a blueprint. The builder copies measurements by hand into a notebook. Months later the blueprint changes, the notebook does not, and a door is built in the wrong place. Generated types replace the notebook with a photocopy made by a machine: when the blueprint changes, the copy is re-made, and the builder's tools complain about every place that no longer fits. The copy cannot tell you whether the building was actually built to the blueprint. That is a different check.

    The previous lesson, API Contracts and Data Transformation, wrote a contract by hand: a schema and twelve example payloads. This lesson is about the other source of a contract, a machine-readable description of the API, and about turning it into TypeScript so that the client's types come from it instead of from someone's reading of it.

    The core idea

    Think of four layers, each with its own question.

    1. The description. What does the API publish about itself? (An OpenAPI document.)
    2. The generated types. Does the client code agree with the description? (Compile time.)
    3. The server. Does the running server agree with the description? (Server-side tests, and contract tests.)
    4. The payload. Does this response, now, agree with the types? (Run time, at the edge.)

    Generation answers question 2 and nothing else. It removes one kind of drift (a hand-copied type that falls behind the description) and leaves the other three questions where they were.

    Figure 1. From description to screen, and what checks each step

    OpenAPI description to generated types to checked edgeOpenAPI to Generator (read); Generator to Generated types (write); Generated types to Edge: check + map (DTO types); CI drift check to Generated types (regenerate and compare)OpenAPI: published contractOpenAPIpublishedcontractGenerator: runs in Node, in a scriptGeneratorruns in Node, ina scriptGenerated types: no run-time codeGeneratedtypesno run-time codeEdge: check + map: run-time checkEdge: check +maprun-time checkCI drift check: types up to date?CI drift checktypes up to date?readwriteDTO typesregenerate and compare

    How to read this: the generator turns a document into types once, in a build step. The types feed the edge's compile-time view, while the edge still checks real payloads at run time. A CI check keeps the generated file from falling behind.

    What an OpenAPI description holds

    The OpenAPI Specification (version 3.2.1 was current when this was written) says an OpenAPI Description "formally describes the surface of an API and its semantics", and that it can be used by documentation tools and by code generation tools to generate servers and clients. For a client, four parts matter:

    Part What a client reads from it
    Paths and operations Which URLs and methods exist, with their parameters
    Request body The media types and the schema of what may be sent
    Responses One entry per status code, optionally a default, with a schema per media type
    Schemas The shape of each object: properties, which are required, types, enums

    The Responses Object "MUST contain at least one response code", may use default for codes not covered individually, and may use ranges written with an uppercase X (2XX covers 200 to 299, and only 1XX to 5XX are allowed); an explicit code takes precedence. A Media Type Object's schema applies to the complete content.

    Schemas have their own rule. By default the Schema Object "is a superset of the JSON Schema Specification Draft 2020-12", so the same ideas as in the last lesson apply: properties are optional unless listed as required, extra properties are allowed unless forbidden, and null is its own type, distinct from an absent property. Two small notes from the specification matter to client authors. readOnly and writeOnly are annotations, and a discriminator "MUST NOT change the validation outcome of the schema".

    From description to types

    The tool named in this lesson is openapi-typescript. Its introduction says it turns OpenAPI 3.0 and 3.1 schemas into TypeScript using Node.js and generates "runtime-free types"; its home page says static types give "zero runtime cost and zero client weight". Its command line writes a file from a schema:

    npx openapi-typescript schema.yaml -o schema.ts

    The same page lists a --check flag, "Check that the generated types are up-to-date", which is what a CI job runs. Other flags change policy; for instance --additional-properties (default false) allows arbitrary properties on every schema object that does not say additionalProperties: false, and --immutable generates readonly properties. The Node API returns a TypeScript syntax tree and offers transform hooks to override how a schema becomes a type.

    At the time of writing, the tool's pages carry a notice that "OpenAPI TypeScript is in maintenance mode". That affects which generator you choose and how much you rely on its newest features; the ideas in this lesson do not depend on one tool.

    Illustration 1 (minimal example): a description and the types it implies

    This OpenAPI fragment is hand-written and illustrative; it was not run through a validator.

    openapi: 3.1.0
    info: { title: Shop API, version: "1.0" }
    paths:
      /products/{id}:
        get:
          parameters:
            - { name: id, in: path, required: true, schema: { type: string } }
          responses:
            "200":
              description: The product
              content:
                application/json:
                  schema: { $ref: "#/components/schemas/Product" }
    components:
      schemas:
        Product:
          type: object
          required: [id, name, price_cents, in_stock, created_at]
          properties:
            id: { type: string }
            name: { type: string }
            price_cents: { type: integer }
            in_stock: { type: boolean }
            created_at: { type: string, format: date-time }
            discount_percent: { type: [integer, "null"] }

    A generator's output has the same ingredients. The tool's Node page shows required properties as name: string;, optional ones as age?: number;, and says a date-time string is generated as updated_at?: string; by default: a string, not a Date. Real output differs in detail, so the next block is a simplified shape written by hand to match what the pages describe (not generator output); it was type-checked with tsc --strict.

    export interface components {
      schemas: {
        Product: {
          id: string;
          name: string;
          price_cents: number;
          in_stock: boolean;
          created_at: string;
          discount_percent?: number | null;
        };
      };
    }

    Two things are visible. TypeScript's number cannot say "whole numbers only". And a date-time string stays a string (the Node page says the same of real output), so the edge from the last lesson still has to produce the Date.

    Using the types: names for the wire, not for the app

    The generated types describe the wire. They belong at the edge, as the DTOs of the previous lesson, and not in components:

    type ProductDto = components["schemas"]["Product"];

    The edge maps ProductDto to the domain Product; everything else depends on the domain type. If the description changes a field, regeneration changes ProductDto, the mapper stops compiling, and the compiler lists the places to fix. That is the real benefit: a contract change turns into compile errors instead of runtime surprises.

    A client library can also take the generated paths type. The openapi-fetch page shows createClient<paths>({ baseUrl }) and says every method returns data, error and response: data holds a 2xx response, error holds a 5xx, 4xx or default response, and response is the original Response. That maps neatly onto the failure kinds of API Integration Basics, but the page I read does not describe checking response bodies at run time, so treat it as a typed convenience, not a validator.

    Figure 2. What each layer can promise

    flowchart TD accTitle: Which layer checks which promise accDescr: Four questions in a row. Does the client code match the description: generated types, compile time. Does the server match the description: server tests and contract tests. Does this payload match the types: run-time check at the edge. Does the user see something sensible when it does not: failure kinds and a fallback in the UI. A["Description changed"] --> B["Client code still matches it?
    Generated types, compile time"] B --> C["Server still matches it?
    Server tests, contract tests"] C --> D["This payload matches the types?
    Run-time check at the edge"] D --> E["User sees something sensible if not?
    Failure kinds, fallback UI"]

    How to read this: each box needs its own mechanism. Generated types only cover the first one, which is why the edge and the failure kinds stay.

    Illustration 2 (realistic example): a product page with a drift check

    A shop's product page reads one product and lists reviews. The API team publishes an OpenAPI document in the same repository as the front end, or at a fixed URL. The front end has a script that regenerates schema.ts from it, commits the result, and a CI step that runs the generator with --check, so a pull request that changes the description without regenerating fails. Components use only domain types; the edge maps the generated DTOs.

    Figure 3. A change in the description, followed through

    sequenceDiagram accTitle: A description change flows to a compile error accDescr: The API team changes a field in the OpenAPI document. CI on the front end regenerates the types and compares them with the committed file. The check fails if they differ. A developer regenerates, the mapper no longer compiles, and the developer fixes the mapper and the fixtures before merging. participant A as API team participant D as OpenAPI document participant CI as Front-end CI participant Dev as Front-end developer A->>D: rename price_cents to price_minor CI->>D: regenerate types, compare with committed file CI-->>Dev: check fails: types out of date Dev->>Dev: regenerate, mapper stops compiling Dev->>Dev: fix mapper and fixtures, then merge

    How to read this: the rename becomes a failing check and a compile error before any user is affected. The server's real behaviour is not part of this loop.

    Illustration 3 (failure case): types that compile and a payload that does not match

    A server bug sends price_cents as the string "12.50" for one currency. The description says integer, the generated type says number, and this compiles:

    const dto: ProductDto = JSON.parse(text); // JSON.parse returns any
    const label = (dto.price_cents / 100).toFixed(2);

    When this was run on Node 26.13.1 with that payload, no error was thrown. The division coerced the string and the label came out as 0.13. The page shows a wrong price with no exception, and the generated type was never involved. The hand-written edge of the last lesson catches this payload: in that lab, a price sent as the string "12.50" fails with the path $.price_cents.

    Trade-offs

    Choice Gains Costs
    Hand-written types No tooling; full control Drift from the description, silently
    Generated types Drift becomes a compile error or a failing check A build step and a good description to generate from
    Generated types plus a hand-written edge Compile-time agreement and run-time checks Two things to maintain
    Generated types plus generated run-time schemas Less hand writing A tool for schemas that this lesson did not evaluate
    Types from shared server code (tRPC) No separate description Needs one TypeScript codebase, see the REST, GraphQL and tRPC lesson

    The other side of this topic

    The server side owns the description: whether it is written first and the server built to it, or produced from server code, and whether server tests prove the two agree. The back-end lessons on API design, API Styles: REST, gRPC, GraphQL and WebSockets and System Design: API Design, are the place to start. Whatever the process, a client should be able to ask the same question of every team: how do you know the description is true?

    In practice: adopting generated types on a shop front end

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A shop's front end has hand-written interfaces for forty response types. Three times in a quarter a field was renamed and the interface was not updated. The API team already keeps an OpenAPI document next to its code. Two front-end and two back-end engineers are involved.

    Starting architecture

    The interfaces live in a types folder, copied from the document by eye. Components import them directly, and each uses a type assertion on response.json().

    Figure 4. Hand-copied types, no check against the document

    Starting architecture: interfaces copied by hand from the OpenAPI documentOpenAPI to types folder (copied by eye); types folder to Components (used as)OpenAPI: API team's fileOpenAPIAPI team's filetypes folder: 40 interfacestypes folder40 interfacesComponents: import types directlyComponentsimport typesdirectlycopied by eyeused as

    How to read this: the dashed arrow is the manual copy. Nothing fails when the document changes and the folder does not.

    Options considered

    Option What it fixes What it costs Risk
    Keep hand-written types, review harder Nothing mechanical Reviewer time The same drift returns
    Generate types, use them everywhere Compile-time drift A script and CI step Components bind to wire names
    Generate types for the edge only; map to domain types Drift is caught, components stay stable A mapper per resource The mapper must be written

    The decision

    Field Decision record
    Context Hand-written interfaces drift from a document the API team already maintains.
    Decision Generate DTO types from the OpenAPI document into one committed file, check it in CI, use it only in the edge, and keep run-time checks and fixtures for the fields that matter most.
    Consequences, good Renames become compile errors; the edge is the only code that knows wire names.
    Consequences, bad A generator to maintain; the document must be accurate for any of this to help.
    Revisit when The generator's maintenance state is a concern, or run-time schemas can be generated from the same document with a tool the team has evaluated.

    Rollout and verification

    1. Generate for one resource and map it at the edge, leaving the rest on hand-written types.
    2. Add the --check step to CI and confirm it fails on a deliberate change to the document.
    3. Keep the fixtures. Replay example payloads through the edge in tests, as in the previous lesson.
    4. Track contract failures by path in production, since generation does not see them.

    The 2 a.m. failure

    Customers report prices of a few cents on one product line. Compile, lint and CI checks were green. The server returns a decimal string for that product line, while the OpenAPI document still says integer. The generated type and the committed code agree with the document, and both disagree with the server.

    First three checks: (1) compare one raw response with the document's schema for that response; (2) check the edge's contract-failure metric for the path; (3) check whether the server's tests include that product line. Mitigation: make the edge reject the payload so the page shows an error state rather than a wrong price. Follow-up: add a server-side contract test, so the document is verified against the server, and add the product line to the fixtures.

    Architect's notes

    • Generate the wire types; write the domain types. They have different jobs.
    • Commit the generated file and check it in CI. A drift check is cheap.
    • Treat the description as a claim about the server. Someone must test it.
    • Keep a run-time edge for the fields where a wrong value costs money or trust.
    • Choose tools with their maintenance state in mind, and keep generated code behind one module.

    Common mistakes

    • Believing "the types are generated, so they are true." They are only as true as the description.
    • Using generated DTOs in components. Wire names leak into the UI.
    • Editing the generated file by hand. The next run overwrites it.
    • Skipping the CI check. The types fall behind quietly.
    • Expecting date-time to become a Date. By default it is a string.

    Key takeaways

    • An OpenAPI description publishes paths, operations, responses per status code, and schemas.
    • Generation produces types with no run-time code; it checks the client against the description only.
    • Use generated types for the wire (DTOs) at the edge; map to domain types.
    • Run the generator's check in CI so the types cannot fall behind.
    • A date-time stays a string by default and number cannot say integer; the edge supplies the rest.
    • The server and the payload still need their own checks.

    Practice exercises

    Exercise 1: Starter (30 min). Write the OpenAPI fragment for one endpoint of a project you know, with a 200 and a 404 response. List which parts a generator can turn into types and which it cannot.

    Exercise 2: Intermediate (2 hours). Generate types for it with the CLI. Write the edge mapper from the DTO to a domain type, and a test that renames a field in the description and shows the compile error.

    Exercise 3: Advanced (half day). Add a CI step that runs the generator with --check. Then write three fixture payloads that disagree with the description in different ways, and decide which layer should catch each.

    In this course:

    This lesson has no lab. The hand-written edge it builds on has a tested lab in the previous lesson.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments