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

JSON only. For a YAML file, convert it to JSON first (an editor command or yq does it), then paste. Runs in your browser; the spec isn't uploaded.

JSON carries dates as strings, so string is the safe default; Date only fits if you convert after parsing.

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?

Mapping used by this page
OpenAPITypeScriptDetail
type: string, integer, number, booleanstring, number, number, booleanformat: binary becomes Blob; date types optionally Date
type: array, itemsT[]3.1 prefixItems becomes a tuple
type: object, properties, required{ key?: T }Optional unless listed in required
additionalProperties[key: string]: Ttrue 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, headerrequest.path, .query, .headercookie parameters are skipped
requestBody contentrequest.bodyJSON first, then form-urlencoded, multipart, text
responses 2xx, defaultOperationResponsedefault counts as success only when no 2xx exists

How to generate TypeScript types from an OpenAPI document

  1. 1
    Paste the document as JSONVersion 3.0 or 3.1. If you have YAML, convert it to JSON first; this page reads JSON only.
  2. 2
    Check 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.
  3. 3
    Choose interface or type, and the extrasTurn the per-operation types and the fetch client on or off, and decide whether descriptions become JSDoc.
  4. 4
    Copy 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?
It has no YAML parser, and guessing at YAML would produce wrong types without warning. Convert the file first with an editor's YAML-to-JSON command or yq and paste the JSON. Nothing else changes: the document is read the same way.
How are nullable fields handled across 3.0 and 3.1?
OpenAPI 3.0 uses nullable: true next to a type. Version 3.1 follows JSON Schema 2020-12, where null is a type and a field is written type: ["string", "null"]. Both come out as string | null.
What is the difference between required and optional here?
A property listed in the schema's required array has no question mark; every other property gets one. For parameters, path parameters are always required, and query or header groups are required only when one of their members is.
What happens to a $ref that can't be resolved?
The type becomes unknown and the reference is listed, with the place it was used and the reason: no such location, a loop, or a pointer to another file or URL. This page works on the one document you paste, so external references need to be inlined first.
Why is an id typed number when the format is int64?
JSON has one number type, and JavaScript reads it as a double, which is exact only up to 2^53 - 1. Ordinary ids fit. If your API uses 64-bit values near the limit, change those fields to string on both ends.
Does the fetch client handle authentication?
No. Security schemes in the spec are listed in the notes but not applied. Pass tokens or keys through createClient({ headers }), or wrap the fetch option to refresh tokens before each call.
Is my API description sent anywhere?
No. Parsing, $ref checking and code generation all happen in the page, so you can paste a private spec.

Sources

Related tools

See all 135 free tools

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