openapi-typescript for TypeScript: Complete Guide with Examples
\n\nIn modern web development, APIs play a key role, and their specification using the OpenAPI standard (formerly Swagger) has become the de facto standard. However, manually maintaining TypeScript types in accordance with the OpenAPI specification is a labor-intensive and error-prone process. The openapi-typescript library solves this problem by automatically generating strict TypeScript types based on your OpenAPI schema (v3.0 and v3.1).
\n\nThe main goal of the library is to provide type-safe interaction with the API. Instead of manually declaring interfaces for each endpoint, you run a generator that creates a single file (or multiple files) with types for all requests, responses, parameters, and schemas. This not only saves time but also ensures that your types are always synchronized with the current version of the API. If the specification changes, you simply regenerate the types, and the TypeScript compiler will immediately point out all inconsistencies in the code.
\n\nThe library is actively used in projects where reliability and development speed are critical: from microservice architectures to SPA applications. It supports generation for both the client side (e.g., for fetch or axios) and the server side (e.g., for Express or Fastify). In this article, we will thoroughly cover installation, main methods, real-world examples, and common mistakes.
\n\nInstallation
\nTo install the library, use npm or yarn. The command will install both the generator itself and the necessary dependencies.
\n\nnpm install openapi-typescript typescript @types/node --save-dev\n\nOr via yarn:
\n\nyarn add -D openapi-typescript typescript @types/node\n\nIf you plan to use the generated types at runtime (e.g., for validation), additionally install openapi-typescript-helpers:
npm install openapi-typescript-helpers\n\nQuick Start — Minimal Working Example
\nSuppose you have a file spec.yaml with an OpenAPI specification. Let's create a simple script to generate types.
// generate.ts\nimport { createClient } from 'openapi-typescript';\nimport * as fs from 'fs';\n\nasync function main() {\n const spec = fs.readFileSync('./spec.yaml', 'utf-8');\n const result = await createClient(spec, { format: 'yaml' });\n fs.writeFileSync('./api-types.d.ts', result);\n console.log('Types generated in api-types.d.ts');\n}\n\nmain().catch(console.error);\n\nRun the script:
\n\nnpx ts-node generate.ts\n\nAfter this, the file api-types.d.ts will contain all the types corresponding to your specification. Now you can import them into your project:
import type { paths, components } from './api-types';\n\n// Using a type for a specific endpoint\ntype GetUsersResponse = paths['/users']['get']['responses'][200]['content']['application/json'];\n\nMain Methods and Functions
\n\n1. createClient(schema: string, options?: ClientOptions): Promise<string>
\nWhat it does: The main method for generating types. It takes a string with the specification (JSON or YAML) and returns a string with TypeScript code.
\nimport { createClient } from 'openapi-typescript';\nimport * as fs from 'fs';\n\nconst spec = fs.readFileSync('./spec.json', 'utf-8');\nconst types = await createClient(spec, { format: 'json' });\nfs.writeFileSync('./types.d.ts', types);\n\n2. createClientFromUrl(url: string, options?: ClientOptions): Promise<string>
\nWhat it does: Asynchronously loads the specification from a URL
Also in library
SwiftConfig: Application Configuration Management in Swift
Kotlin Task Scheduler: kotlinx.coroutines and Libraries for Background Tasks
PDF Generation in PHP: Best Libraries and Code Examples
JWT tokens in Rust: jsonwebtoken library and authentication
Caching in Rust: Redis, Memcached, and Built-in Solutions