Skip to content

openapi-typescript

Developer UtilitiesUtilityTypeScript

What it is

openapi-typescript generates TypeScript types from an OpenAPI schema, giving a typed client for an API you do not control.

Generate a types file from a schema URL or path, then use openapi-fetch for a client where paths, parameters and responses are all checked.

Installation

npm install -D openapi-typescript && npm install openapi-fetch

Getting started

The smallest useful thing you can do with it, and what each part means.

Generated types and a typed client
import createClient from 'openapi-fetch';
import type { paths } from './api';

const client = createClient<paths>({ baseUrl: 'https://api.example.com' });

const { data, error } = await client.GET('/books/{id}', {
  params: { path: { id: '42' } },
});

if (error) return handle(error);   // error is typed from the schema too
console.log(data.title);           // typed from the 200 response
The path string is checked against the schema, so a typo or a removed endpoint is a compile error. Both success and error shapes come from the document.

Advanced usage

Where the library earns its place over a simpler alternative.

Keeping generated types honest in CI
{
  "scripts": {
    "api:generate": "openapi-typescript https://api.example.com/openapi.json -o src/api.d.ts",
    "api:check": "npm run api:generate && git diff --exit-code src/api.d.ts"
  }
}
Running api:check in CI fails the build when the upstream API changed and nobody regenerated — turning a silent runtime break into a visible one.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

Generated types are full of unknown
The schema lacks response definitions. Improve the OpenAPI document — the generator can only reflect what it is given.
data is possibly undefined
Correct: either data or error is set. Narrow with an if (error) return before using data.

Best practices

  • Commit the generated file so builds do not depend on the API being reachable.
  • Regenerate in CI and fail on a diff, so upstream changes surface immediately.
  • Use openapi-fetch rather than raw fetch to get path and parameter checking.
  • Prefer tRPC when you own both ends; use this when you do not.

Background

Why it exists, and what it was reacting to.

It solves the other half of the type-safety problem tRPC addresses: when the server is not TypeScript, the OpenAPI document is the contract, and this turns it into types automatically.