Type-Safe API Contracts: End-to-End Inference from OpenAPI to Your UI
Mar 18, 20264 min read
Every team eventually hits the same bug: the backend renames a field, ships on
Tuesday, and the frontend starts rendering undefined where a price used to
be. The runtime error surfaces Thursday. TypeScript catches none of it,
because both sides have their own hand-written types and neither one is the
truth.
The fix isn't discipline. It's making the contract structural — generated from one source, validated at the boundary, and threaded through the client so the compiler does the work.
The drift problem#
Hand-written API types drift in exactly three ways:
- Renames —
user_idbecomesuserIdon one side only. - Nullability — a field becomes optional; the client still assumes it exists.
- Shape changes — a list becomes a paginated envelope; the client keeps treating it as an array.
Each one is a runtime bug that survives review, because nothing in the type system connects the two codebases.
The contract is the API
The OpenAPI (or GraphQL) schema is the API. Code on both sides is a derivation of it. Once you treat the schema as the source of truth, types stop being documentation and start being infrastructure.
Generating types from OpenAPI#
openapi-typescript reads your spec and emits a .d.ts that is exactly as
good as your spec. The output is plain, readable, and versionable:
npx openapi-typescript https://api.internal/spec.yaml -o src/api/schema.d.tsThe generated file gives you the full request/response surface:
export interface paths {
"/v1/orders": {
get: operations["listOrders"];
post: operations["createOrder"];
};
}
export interface components {
schemas: {
Order: {
id: string;
amount_cents: number;
status: "pending" | "paid" | "refunded";
line_items: components["schemas"]["LineItem"][];
};
};
}Now the compiler knows the truth — but only if you actually use these types. A generated file nobody imports is a decoration.
Runtime validation at the edge of the system#
Generated types are compile-time only. The network still hands you bytes, and bytes can lie — a hotfix deployed to prod, a gateway that strips a field, a third-party webhook that changed shape overnight.
This is where a runtime schema earns its keep. Generate zod schemas from the same spec (or derive them), and validate every response:
import { z } from "zod";
import type { components } from "./schema.d.ts";
// Generated from the same OpenAPI spec.
const orderSchema = z.object({
id: z.string(),
amount_cents: z.number(),
status: z.enum(["pending", "paid", "refunded"]),
line_items: z.array(lineItemSchema),
});
type Order = components["schemas"]["Order"];
export async function getOrder(id: string): Promise<Order> {
const res = await fetch(`/api/v1/orders/${id}`);
if (!res.ok) throw new ApiError(res.status, await res.text());
const data: unknown = await res.json();
return orderSchema.parse(data);
}parse throws on mismatch. In development that's an immediate, stack-traced
failure at the exact field. In production you log it with the raw payload
attached — and now every schema drift becomes an observable, alertable event
instead of a screenshot from a confused user.
Fail at the boundary, not in the UI
A validation error at the fetch layer is cheap to diagnose: you have the payload, the route, and the schema in the same log line. The same bug surfacing three components deep in a render tree costs an afternoon.
A typed fetch layer#
Once responses are validated, you can build a client where the URL is the type. Route functions map paths to their schemas, so a wrong parameter or a wrong return type is a compile error:
import type { paths } from "./schema.d.ts";
type Get<S extends keyof paths, P extends keyof paths[S]> = paths[S][P] extends
{ get: infer G }
? G extends { parameters?: infer Params }
? { params: Params }
: { params?: never }
: never;
export const api = {
get: async <
S extends keyof paths,
P extends keyof paths[S],
R extends Get<S, P>,
>(
path: S & string,
args: R["params"] & {},
): Promise<paths[S][P] extends { get: { responses: { 200: infer B } } }
? B extends { content: { "application/json": infer J } } ? J : never
: never> => {
const res = await fetch(path, args as RequestInit);
return res.json();
},
};
// Compiles — the compiler knows the response shape.
const orders = await api.get("/v1/orders", {
params: { query: { status: "paid" } },
});This is the moment the type system starts leading you: autocomplete on paths, errors on misspelled query params, and a response type that flows into your components without a single cast.
The trade-offs, honestly#
Generated code has a cost
You're coupling your client's build to the spec's quality. A sloppy spec
(anyOf: [string, null] everywhere) produces types that compile but lie.
Invest in the spec first — make nullability explicit, name your enums, and
review spec changes like code.
Generation also adds a step to local setup. I think that's the right trade — the alternative is hand-synchronizing types across two codebases forever, which is exactly the drift we set out to kill.
Wrapping up#
The pattern is a pipeline: one spec → generated types → runtime validation → typed client. Each layer catches what the previous one can't:
- The spec is the single source of truth.
- Generated types catch drift at compile time.
- Zod schemas catch drift at the network boundary.
- The typed client makes the happy path ergonomic.
The best part: once it's in place, nobody thinks about it. The compiler complains, the validation fails, and the bug never reaches a user.