π Convert OpenAPI 3.0 and 2.0 (Swagger) schemas to TypeScript interfaces using Node.js.
Features
- Convert Open API 3.x and Swagger 2.x to TypeScript types
- Load schemas either from local
.yaml
or.json
files, or from a remote URL (simple authentication supported with the--auth
flag) - Supports remote
$ref
s using json-schema-ref-parser - Formats output using Prettier
- Uses the latest TypeScript 4.0 syntax
Examples
npx openapi-typescript schema.yaml --output schema.ts
# π Loading spec from schema.yamlβ¦
# π schema.yaml -> schema.ts [250ms]
npx openapi-typescript "specs/**/*.yaml" --output schemas/
# π Loading spec from specs/one.yamlβ¦
# π Loading spec from specs/two.yamlβ¦
# π Loading spec from specs/three.yamlβ¦
# π specs/one.yaml -> schemas/specs/one.ts [250ms]
# π specs/two.yaml -> schemas/specs/two.ts [250ms]
# π specs/three.yaml -> schemas/specs/three.ts [250ms]
Note: if generating a single schema, --output
must be a file (preferably *.ts
). If using globs, --output
must be a directory.
Thanks to @sharmarajdaksh for the glob feature!
npx openapi-typescript https://petstore.swagger.io/v2/swagger.json --output petstore.ts
# π Loading spec from https://petstore.swagger.io/v2/swagger.jsonβ¦
# π https://petstore.swagger.io/v2/swagger.json -> petstore.ts [650ms]
Note: for obvious reasons, globbing doesnβt work for remote schemas
Thanks to @psmyrdek for the remote spec feature!
Import any top-level item from the generated spec to use it. It works best if you also alias types to save on typing:
import { components } from './generated-schema.ts';
type APIResponse = components["schemas"]["APIResponse"];
The reason for all the ["β¦"]
everywhere is because OpenAPI lets you use more characters than are valid TypeScript identifiers. The goal of this project is to generate all of your schema, not merely the parts that are βTypeScript-safe.β
Also note that thereβs a special operations
interface that you can import OperationObjects
by their operationId:
import { operations } from './generated-schema.ts';
type getUsersById = operations["getUsersById"];
This is the only place where our generation differs from your schema as-written, but itβs done so as a convenience and shouldnβt cause any issues (you can still use deep references as-needed).
Thanks to @gr2m for the operations feature!
npx openapi-typescript schema.yaml
Option | Alias | Default | Description |
---|---|---|---|
--output [location] |
-o |
(stdout) | Where should the output file be saved? |
--auth [token] |
(optional) Provide an auth token to be passed along in the request (only if accessing a private schema) | ||
--immutable-types |
-it |
false |
(optional) Generates immutable types (readonly properties and readonly array) |
--additional-properties |
-ap |
false |
(optional) Allow arbitrary properties for all schema objects without additionalProperties: false
|
--default-non-nullable |
false |
(optional) Treat schema objects with default values as non-nullable | |
--prettier-config [location] |
-c |
(optional) Path to your custom Prettier configuration for output | |
--raw-schema |
false |
Generate TS types from partial schema (e.g. having components.schema at the top level) |
npm i --save-dev openapi-typescript
const fs = require("fs");
const openapiTS = require("openapi-typescript").default;
// option 1: load [object] as schema (JSON only)
const schema = await fs.promises.readFile("spec.json", "utf8") // must be OpenAPI JSON
const output = await openapiTS(JSON.parse(schema));
// option 2: load [string] as local file (YAML or JSON; released in v3.3)
const localPath = path.join(__dirname, 'spec.yaml'); // may be YAML or JSON format
const output = await openapiTS(localPath);
// option 3: load [string] as remote URL (YAML or JSON; released in v3.3)
const output = await openapiTS('https://myurl.com/v1/openapi.yaml');
The Node API may be useful if dealing with dynamically-created schemas, or youβre using within context of a larger application. Pass in either a JSON-friendly object to load a schema from memory, or a string to load a schema from a local file or remote URL (it will load the file quickly using built-in Node methods). Note that a YAML string isnβt supported in the Node.js API; either use the CLI or convert to JSON using js-yaml first.
v3.3
, this is an async function.
If using the Node.js API, you can optionally pass a formatter to openapi-typescript. This is useful if you want to override the default types and substitute your own.
For example, say your schema has the following property:
properties:
updated_at:
type: string
format: date-time
By default, this will generate a type updated_at?: string;
. But we can override this by passing a formatter to the Node API, like so:
const types = openapiTS(mySchema, {
formatter(node: SchemaObject) {
if (node.format === 'date-time') {
return "Date"; // return the TypeScript βDateβ type, as a string
}
// for all other schema objects, let openapi-typescript decide (return undefined)
});
This will generate updated_at?: Date
instead. Note that you will still have to do the parsing of your data yourself. But this will save you from having to also update all your types.
Note: you donβt have to use .format
βthis is just an example! You can use any property on a schema object to overwrite its generated type if desired.
- Support converting any OpenAPI 3.0 or 2.0 (Swagger) schema to TypeScript types, no matter how complicated
- The generated TypeScript types must match your schema as closely as possible (i.e. donβt convert names to
PascalCase
or follow any TypeScript-isms; faithfully reproduce your schema as closely as possible, capitalization and all) - This library is a TypeScript generator, not a schema validator.
PRs are welcome! Please see our CONTRIBUTING.md guide. Opening an issue beforehand to discuss is encouraged but not required.
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!