OpenAPI to TypeScript types and typed fetch client
Paste an OpenAPI 3.0 or 3.1 document as JSON and get TypeScript types for components.schemas (allOf, oneOf, enum, nullable, required, $ref), a request and response type for each operation, and a small typed fetch client. Every $ref is checked and unresolved ones are listed.
Updated
TypeScript types
7 schemas, 4 operations
all $refs resolve
- Pass · $refs resolve11 $refs checked, all found
- Pass · OpenAPI versionopenapi 3.0.3
TypeScript (types + client)
// ── components.schemas ──
export type PetStatus = "available" | "pending" | "sold";
export interface NewPet {
name: string;
tag?: string | null;
status?: PetStatus;
}
export type Pet = NewPet & {
id: number;
born?: string;
};
export interface Cat {
kind: "cat";
indoor?: boolean;
}
export interface Dog {
kind: "dog";
breed?: string;
}
export type Animal = Cat | Dog;
export interface Problem {
title: string;
status: number;
detail?: string;
}
// ── operations ──
/** GET /pets: List pets */
export interface ListPetsRequest {
query?: {
limit?: number;
status?: PetStatus;
};
}
export type ListPetsResponse = Pet[];
export type ListPetsError = Problem;
// POST /pets
export interface CreatePetRequest {
body: NewPet;
}
export type CreatePetResponse = Pet;
// GET /pets/{petId}
export interface GetPetRequest {
path: {
petId: number;
};
}
export type GetPetResponse = Animal;
export type GetPetError = Problem;
// DELETE /pets/{petId}
export interface DeletePetRequest {
path: {
petId: number;
};
}
export type DeletePetResponse = void;
// ── typed fetch client ──
export interface ClientOptions {
baseUrl?: string;
headers?: HeadersInit; // put API keys or bearer tokens here
fetch?: typeof fetch;
}
export class ApiError extends Error {
constructor(
public status: number,
public body: unknown,
) {
super(`HTTP ${status}`);
}
}
interface RequestInput {
path?: Record<string, unknown>;
query?: Record<string, unknown>;
header?: Record<string, unknown>;
body?: unknown;
}
async function readBody(res: Response): Promise<unknown> {
if (res.status === 204) return undefined;
const type = res.headers.get("content-type") ?? "";
if (type.includes("json")) {
const text = await res.text();
return text ? JSON.parse(text) : undefined;
}
if (type.startsWith("text/")) return res.text();
return res.blob();
}
async function send<T>(
opts: ClientOptions & { baseUrl: string },
method: string,
route: string,
input: RequestInput = {},
contentType?: string,
): Promise<T> {
const url = route.replace(/\{([^}]+)\}/g, (_, name) => encodeURIComponent(String(input.path?.[name])));
const search = new URLSearchParams();
for (const [k, v] of Object.entries(input.query ?? {})) {
if (v === undefined || v === null) continue;
for (const item of Array.isArray(v) ? v : [v]) search.append(k, String(item));
}
const headers = new Headers(opts.headers);
for (const [k, v] of Object.entries(input.header ?? {})) if (v !== undefined && v !== null) headers.set(k, String(v));
let body: BodyInit | undefined;
if (input.body !== undefined) {
if (contentType === "multipart/form-data") {
const form = new FormData();
for (const [k, v] of Object.entries(input.body as Record<string, unknown>)) form.append(k, v instanceof Blob ? v : String(v));
body = form; // fetch sets the multipart boundary itself
} else if (contentType === "application/x-www-form-urlencoded") {
body = new URLSearchParams(Object.entries(input.body as Record<string, unknown>).map(([k, v]) => [k, String(v)]));
} else if (contentType === "application/json") {
headers.set("Content-Type", contentType);
body = JSON.stringify(input.body);
} else {
if (contentType) headers.set("Content-Type", contentType);
body = input.body as BodyInit;
}
}
const qs = search.toString();
const res = await (opts.fetch ?? fetch)(`${opts.baseUrl}${url}${qs ? `?${qs}` : ""}`, { method, headers, body });
if (!res.ok) throw new ApiError(res.status, await readBody(res));
return (await readBody(res)) as T;
}
export function createClient(options: ClientOptions = {}) {
const opts = { ...options, baseUrl: (options.baseUrl ?? "https://api.petshop.example/v1").replace(/\/+$/, "") };
return {
listPets: (req: ListPetsRequest = {}) => send<ListPetsResponse>(opts, "GET", "/pets", req),
createPet: (req: CreatePetRequest) => send<CreatePetResponse>(opts, "POST", "/pets", req, "application/json"),
getPet: (req: GetPetRequest) => send<GetPetResponse>(opts, "GET", "/pets/{petId}", req),
deletePet: (req: DeletePetRequest) => send<DeletePetResponse>(opts, "DELETE", "/pets/{petId}", req),
};
}- Fields with format int64 are typed number; a JavaScript number is exact only up to 2^53 - 1, so very large ids may need to travel as strings.
How does an OpenAPI document become TypeScript?
Each entry in components.schemas becomes an exported type. required lists decide which properties get a question mark. allOf becomes an intersection (A & B), oneOf and anyOf become unions (A | B), enum becomes a union of literals, and nullable: true in 3.0 or a type array with "null" in 3.1 adds | null. additionalProperties becomes an index signature. A $ref to another schema becomes that schema's type name, so shared shapes stay shared.
For every operation under paths the page writes a request type with path, query, header and body groups (a group is required only if one of its members is) and a response type, which is the union of the 2xx bodies. Path-level parameters are merged with the operation's own, and the operation wins on a clash. Error responses, when listed, become a separate error type.
Every $ref in the document is followed before conversion. One that points to a missing location, loops forever, or leaves the document is listed with where it was used, and the type it would have produced is unknown. The optional fetch client is about 70 lines with one function per operation, filled-in path parameters, query serialization, JSON or form bodies, and an ApiError thrown for non-2xx responses.
allOf: [A, B] -> A & B oneOf: [A, B] -> A | B type: ["string","null"] -> string | null (3.1) nullable: true -> T | null (3.0) required: ["id"] -> id: T; other keys -> key?: T;
Which OpenAPI keyword turns into which TypeScript?
| OpenAPI | TypeScript | Detail |
|---|---|---|
| type: string, integer, number, boolean | string, number, number, boolean | format: binary becomes Blob; date types optionally Date |
| type: array, items | T[] | 3.1 prefixItems becomes a tuple |
| type: object, properties, required | { key?: T } | Optional unless listed in required |
| additionalProperties | [key: string]: T | true becomes unknown |
| enum, const | "a" | "b" | null in the list becomes null |
| allOf, oneOf, anyOf | &, |, | | discriminator is read as a plain union |
| nullable (3.0), type array with null (3.1) | T | null | |
| parameters in path, query, header | request.path, .query, .header | cookie parameters are skipped |
| requestBody content | request.body | JSON first, then form-urlencoded, multipart, text |
| responses 2xx, default | OperationResponse | default counts as success only when no 2xx exists |
How to generate TypeScript types from an OpenAPI document
- 1Paste the document as JSONVersion 3.0 or 3.1. If you have YAML, convert it to JSON first; this page reads JSON only.
- 2Check the $ref resultA green line means every reference resolves. A red one lists each broken reference, where it is used and why, so you can fix the spec at the source.
- 3Choose interface or type, and the extrasTurn the per-operation types and the fetch client on or off, and decide whether descriptions become JSDoc.
- 4Copy into your projectSave the output as a .ts file, call createClient({ baseUrl, headers }) and use the typed functions. Add your token to headers; security schemes are not applied for you.
Frequently asked questions
Why does this page only accept JSON, not YAML?
How are nullable fields handled across 3.0 and 3.1?
What is the difference between required and optional here?
What happens to a $ref that can't be resolved?
Why is an id typed number when the format is int64?
Does the fetch client handle authentication?
Is my API description sent anywhere?
Sources
- OpenAPI Specification 3.1.1 (parameters in path/query/header/cookie, request bodies, path-level parameters, JSON Schema 2020-12 types) (checked 11 Nov 2026)
- OpenAPI Specification 3.0.3 (nullable, Schema Object) (checked 11 Nov 2026)
- RFC 6901: JSON Pointer (how a $ref fragment is resolved) (checked 11 Nov 2026)
- RFC 8259: The JSON Data Interchange Format (checked 11 Nov 2026)
Need a custom dev tool for your team?
We build internal tools, dashboards, APIs, and SaaS platforms. If you can describe it, we can ship it.
Built by CountryDevs · No signup · No ads · We count visits, never what you enter