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-fetchGetting started
The smallest useful thing you can do with it, and what each part means.
typescript
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 responseAdvanced usage
Where the library earns its place over a simpler alternative.
json
{
"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"
}
}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.
