{"id":11498,"library":"openapi-typescript","title":"OpenAPI to TypeScript Type Generator","description":"openapi-typescript is a powerful command-line tool and library designed to convert OpenAPI 3.0 and 3.1 specifications into TypeScript type definitions. It produces runtime-free, statically-analyzable types, enabling robust type safety for API clients, facilitating validation of mock data, and streamlining the development of business logic directly from your API's schema. The current stable version is 7.13.0, and the project maintains a healthy and active release cadence, frequently publishing minor or patch versions across its ecosystem of packages (e.g., openapi-typescript, openapi-fetch). A key differentiator is its speed and its minimal dependency footprint, requiring only Node.js and avoiding external runtimes like Java, making it a lightweight and efficient alternative to many traditional OpenAPI codegen solutions. It supports loading schemas from local YAML or JSON files, as well as remote URLs.","status":"active","version":"7.13.0","language":"javascript","source_language":"en","source_url":"https://github.com/openapi-ts/openapi-typescript","tags":["javascript","swagger","typescript","ts","dts","openapi","codegen","generation","openapi 3"],"install":[{"cmd":"npm install openapi-typescript","lang":"bash","label":"npm"},{"cmd":"yarn add openapi-typescript","lang":"bash","label":"yarn"},{"cmd":"pnpm add openapi-typescript","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for consuming the generated types and for the library's internal TypeScript usage.","package":"typescript","optional":false}],"imports":[{"note":"This is for programmatic usage of the generator. The primary CLI usage does not involve this import.","wrong":"import { openapiTS } from 'openapi-typescript';","symbol":"openapiTS","correct":"import openapiTS from 'openapi-typescript';"},{"note":"Imported from the *generated* TypeScript definition file, typically with `type` keyword for compile-time usage only. The path depends on your output file.","wrong":"import { paths } from './my-openapi-3-schema';","symbol":"paths","correct":"import type { paths } from './my-openapi-3-schema';"},{"note":"Imported from the *generated* TypeScript definition file, typically with `type` keyword for compile-time usage only. Provides access to schema definitions. The path depends on your output file.","wrong":"import { components } from './my-openapi-3-schema';","symbol":"components","correct":"import type { components } from './my-openapi-3-schema';"}],"quickstart":{"code":"import { createClient } from '@hey-api/openapi-ts'; // For programmatic usage\nimport { writeFile } from 'node:fs/promises';\nimport type { paths, components } from './generated-api-types'; // Example usage of generated types\n\nasync function generateAndUseTypes() {\n  // 1. Generate types using the CLI (most common)\n  console.log('Generating types via CLI...');\n  try {\n    const { execa } = await import('execa');\n    await execa('npx', [\n      'openapi-typescript',\n      'https://petstore.swagger.io/v2/swagger.json', // Or a local file: './path/to/my/schema.yaml'\n      '-o',\n      './generated-api-types.d.ts',\n    ], { stdio: 'inherit' });\n    console.log('Types generated successfully to generated-api-types.d.ts');\n\n    // 2. Or, programmatically (uncomment to use)\n    // const petstoreSchema = await (await fetch('https://petstore.swagger.io/v2/swagger.json')).json();\n    // const types = await openapiTS(petstoreSchema);\n    // await writeFile('./generated-api-types.d.ts', types);\n    // console.log('Types generated programmatically to generated-api-types.d.ts');\n\n    // 3. Example usage of generated types in your application\n    type Pet = components['schemas']['Pet'];\n    type CreatePetRequest = paths['/pet']['post']['requestBody']['content']['application/json'];\n    type GetPetByIdResponse = paths['/pet/{petId}']['get']['responses']['200']['schema'];\n\n    const myPet: Pet = {\n      id: 1,\n      name: 'Buddy',\n      status: 'available',\n      category: { id: 101, name: 'Dogs' },\n      photoUrls: ['http://example.com/buddy.jpg']\n    };\n    console.log('Example Pet type:', myPet);\n\n    const newPetRequest: CreatePetRequest = {\n      name: 'Fluffy',\n      photoUrls: ['http://example.com/fluffy.png'],\n      tags: [{ id: 1, name: 'cute' }]\n    };\n    console.log('Example CreatePetRequest type:', newPetRequest);\n\n  } catch (error) {\n    console.error('Error during type generation or usage:', error);\n    process.exit(1);\n  }\n}\n\ngenerateAndUseTypes();","lang":"typescript","description":"This quickstart demonstrates how to generate TypeScript types from an OpenAPI schema using the `openapi-typescript` CLI and then how to import and use the generated `paths` and `components` types in a TypeScript application to ensure type safety for API interactions. It fetches a remote Swagger Petstore schema for demonstration."},"warnings":[{"fix":"Upgrade your OpenAPI schema to 3.0 or 3.1, or downgrade `openapi-typescript` to a 5.x version if OpenAPI 2.x support is essential.","message":"OpenAPI 2.x (Swagger) specifications are no longer supported by `openapi-typescript` starting from version 6.x. Users with older schemas must use `openapi-typescript` v5.x or earlier.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Consult the migration guide for 7.x on the official documentation site. Update your build scripts, programmatic API calls, and potentially introduce a `redocly.config.yml` file.","message":"Version 7.x introduced several breaking changes, including the handling of remote schema fetching via Redocly CLI (requiring `redocly.config.yml` for auth), changes to the Node.js API input types (requiring URLs for file paths), and `defaultNonNullable: true` by default. Globbing for multiple schemas was also replaced by Redocly configuration.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Add `\"noUncheckedIndexedAccess\": true` to your `compilerOptions` in `tsconfig.json`.","message":"For optimal type safety and to prevent common runtime errors with indexed access, it is highly recommended to enable `noUncheckedIndexedAccess: true` in your `tsconfig.json`. Without it, TypeScript may allow accessing arbitrary keys on objects without checking for existence, leading to `undefined` runtime errors.","severity":"gotcha","affected_versions":">=6.0.0"},{"fix":"Update your `compilerOptions` in `tsconfig.json` to include `\"module\": \"ESNext\"` and `\"moduleResolution\": \"Bundler\"`.","message":"To correctly resolve generated type modules, your `tsconfig.json` should have `\"module\": \"ESNext\"` (or `\"NodeNext\"`) and `\"moduleResolution\": \"Bundler\"` (or `\"NodeNext\"`) under `compilerOptions`. Incorrect settings can lead to TypeScript failing to find the generated types.","severity":"gotcha","affected_versions":">=6.0.0"},{"fix":"If using this flag, ensure your consuming code and any associated client libraries (like `openapi-fetch`) are compatible with these type markers. Adjust your code to use the `Readable<T>` or `Writable<T>` helpers if you need to filter these properties.","message":"The `--read-write-markers` flag (introduced in 7.13.0) will wrap `readOnly` properties with `$Read<T>` and `writeOnly` properties with `$Write<T>`. If you use `openapi-fetch`, it leverages `Readable<T>` and `Writable<T>` helpers to exclude these properties. Be aware that enabling this flag changes the generated type structure for such properties.","severity":"gotcha","affected_versions":">=7.13.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure the output file path in your `npx openapi-typescript` command matches the import path in your TypeScript files. Verify your `tsconfig.json` includes the directory of the generated file and has correct `moduleResolution` settings (e.g., `\"moduleResolution\": \"Bundler\"`). Run the generation command before TypeScript compilation.","cause":"The TypeScript compiler cannot locate the generated type definition file, often due to an incorrect import path, missing `tsconfig.json` configuration, or the file not being generated.","error":"Cannot find module './my-openapi-3-schema' or its corresponding type declarations."},{"fix":"Enable `\"noUncheckedIndexedAccess\": true` in your `tsconfig.json`. Alternatively, use optional chaining (`?.`), nullish coalescing (`??`), or explicit `if` checks to safely access properties.","cause":"This common TypeScript error arises when accessing object properties that might not exist, especially in schemas where `additionalProperties` are allowed or when properties are optional. It's often exacerbated if `noUncheckedIndexedAccess` is not enabled.","error":"Property 'someProperty' is possibly 'undefined'."},{"fix":"Review the programmatic usage documentation for `openapi-typescript` (e.g., `import openapiTS from 'openapi-typescript'; await openapiTS(input);`). If using `@hey-api/openapi-ts`, ensure you're using `createClient` correctly with its specific configuration.","cause":"This error typically occurs in programmatic usage when attempting to access a 'client' property on an `Options` object, which is not part of the standard `openapi-typescript` programmatic API. It might be an attempt to use a feature from a different OpenAPI generation tool or an older, incompatible API version.","error":"TS2339: Property 'client' does not exist on type 'Options'."},{"fix":"Update your OpenAPI specification to version 3.0 or 3.1. If this is not possible, downgrade `openapi-typescript` to a 5.x version, which supports OpenAPI 2.x schemas.","cause":"The input OpenAPI schema specifies a version other than 3.0 or 3.1, such as 2.x (Swagger), which is no longer supported by recent versions of `openapi-typescript`.","error":"Error: \"The OpenAPI document has an invalid version.\""}],"ecosystem":"npm"}