openapi-typescript
TypeScript icon, indicating that this package has built-in type declarations

2.3.4 โ€ข Public โ€ข Published

version(scoped) codecov

All Contributors

๐Ÿ“˜๏ธ openapi-typescript

๐Ÿš€ Convert OpenAPI 3.0 and OpenAPI 2.0 (Swagger) schemas to TypeScript interfaces using Node.js.

๐Ÿ’… The output is prettified with Prettier (and can be customized!).

๐Ÿ‘‰ Works for both local and remote resources (filesystem and HTTP).

View examples:

Usage

CLI

๐Ÿ—„๏ธ Reading specs from file system

npx openapi-typescript schema.yaml --output schema.ts

# ๐Ÿคž Loading spec from tests/v2/specs/stripe.yamlโ€ฆ
# ๐Ÿš€ schema.yaml -> schema.ts [250ms]

โ˜๏ธ Reading specs from remote resource

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]

Thanks to @psmyrdek for this feature!

Generating multiple schemas

In your package.json, for each schema youโ€™d like to transform add one generate:specs:[name] npm-script. Then combine them all into one generate:specs script, like so:

"scripts": {
  "generate:specs": "npm run generate:specs:one && npm run generate:specs:two && npm run generate:specs:three",
  "generate:specs:one": "npx openapi-typescript one.yaml -o one.ts",
  "generate:specs:two": "npx openapi-typescript two.yaml -o two.ts",
  "generate:specs:three": "npx openapi-typescript three.yaml -o three.ts"
}

You can even specify unique options per-spec, if needed. To generate them all together, run:

npm run generate:specs

Rinse and repeat for more specs.

For anything more complicated, or for generating specs dynamically, you can also use the Node API.

CLI Options

Option Alias Default Description
--output [location] -o (stdout) Where should the output file be saved?
--prettier-config [location] (optional) Path to your custom Prettier configuration for output

Node

npm i --save-dev openapi-typescript
const { readFileSync } = require("fs");
const swaggerToTS = require("openapi-typescript");

const input = JSON.parse(readFileSync("spec.json", "utf8")); // Input can be any JS object (OpenAPI format)
const output = swaggerToTS(input); // Outputs TypeScript defs as a string (to be parsed, or written to a file)

The Node API is a bit more flexible: it will only take a JS object as input (OpenAPI format), and return a string of TS definitions. This lets you pull from any source (a Swagger server, local files, etc.), and similarly lets you parse, post-process, and save the output anywhere.

If your specs are in YAML, youโ€™ll have to convert them to JS objects using a library such as js-yaml. If youโ€™re batching large folders of specs, glob may also come in handy.

PropertyMapper

In order to allow more control over how properties are parsed, and to specifically handle x-something-properties, the propertyMapper option may be specified as the optional 2nd parameter.

This is a function that, if specified, is called for each property and allows you to change how openapi-typescript handles parsing of Swagger files.

An example on how to use the x-nullable property to control if a property is optional:

const getNullable = (d: { [key: string]: any }): boolean => {
  const nullable = d["x-nullable"];
  if (typeof nullable === "boolean") {
    return nullable;
  }
  return true;
};

const output = swaggerToTS(swagger, {
  propertyMapper: (swaggerDefinition, property): Property => ({
    ...property,
    optional: getNullable(swaggerDefinition),
  }),
});

Thanks to @atlefren for this feature!

Upgrading from v1 to v2

Some options were removed in openapi-typescript v2 that will break apps using v1, but it does so in exchange for more control, more stability, and more resilient types.

TL;DR:

-import { OpenAPI2 } from './generated';
+import { definitions } from './generated';

-type MyType = OpenAPI2.MyType;
+type MyType = definitions['MyType'];

In-depth explanation

In order to explain the change, letโ€™s go through an example with the following Swagger definition (partial):

swagger: 2.0
definitions:
  user:
    type: object
    properties:
      role:
        type: object
        properties:
          access:
            enum:
              - admin
              - user
  user_role:
    type: object
      role:
        type: string
  team:
    type: object
    properties:
      users:
        type: array
        items:
          $ref: user

This is how v1 would have generated those types:

declare namespace OpenAPI2 {
  export interface User {
    role?: UserRole;
  }
  export interface UserRole {
    access?: "admin" | "user";
  }
  export interface UserRole {
    role?: string;
  }
  export interface Team {
    users?: User[];
  }
}

Uh oh. It tried to be intelligent, and keep interfaces shallow by transforming user.role into UserRole. However, we also have another user_role entry that has a conflicting UserRole interface. This is not what we want.

v1 of this project made certain assumptions about your schema that donโ€™t always hold true. This is how v2 generates types from that same schema:

export interface definitions {
  user: {
    role?: {
      access?: "admin" | "user";
    };
  };
  user_role: {
    role?: string;
  };
  team: {
    users?: definitions["user"][];
  };
}

This matches your schema more accurately, and doesnโ€™t try to be clever by keeping things shallow. Itโ€™s also more predictable, with the generated types matching your schema naming. In your code hereโ€™s what would change:

-UserRole
+definitions['user']['role'];

While this is a change, itโ€™s more predictable. Now you donโ€™t have to guess what user_role was renamed to; you simply chain your type from the Swagger definition youโ€˜re used to.

Better $ref generation

openapi-typescript v1 would attempt to resolve and flatten $refs. This was bad because it would break on circular references (which both Swagger and TypeScript allow), and resolution also slowed it down.

In v2, your $refs are preserved as-declared, and TypeScript does all the work. Now the responsibility is on your schema to handle collisions rather than openapi-typescript, which is a better approach in general.

No Wrappers

The --wrapper CLI flag was removed because it was awkward having to manage part of your TypeScript definition in a CLI flag. In v2, simply compose the wrapper yourself however youโ€™d like in TypeScript:

import { components as Schema1 } from './generated/schema-1.ts';
import { components as Schema2 } from './generated/schema-2.ts';

declare namespace OpenAPI3 {
  export Schema1;
  export Schema2;
}

No CamelCasing

The --camelcase flag was removed because it would mangle object names incorrectly or break trying to sanitize them (for example, you couldnโ€™t run camelcase on a schema with my.obj and my-objโ€”they both would transfom to the same thing causing unexpected results).

OpenAPI allows for far more flexibility in naming schema objects than JavaScript, so that should be carried over from your schema. In v2, the naming of generated types maps 1:1 with your schema name.

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Drew Powers

๐Ÿ’ป ๐Ÿ“– ๐Ÿš‡ โš ๏ธ

Przemek Smyrdek

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Dan Enman

๐Ÿ› ๐Ÿ’ป

Atle Frenvik Sveen

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Tim de Wolf

๐Ÿ’ป ๐Ÿค”

Tom Barton

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Sven Nicolai Viig

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Sorin Davidoi

๐Ÿ› ๐Ÿ’ป โš ๏ธ

Nathan Schneirov

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Lucien Bรฉniรฉ

๐Ÿ’ป ๐Ÿ“– ๐Ÿค” โš ๏ธ

Boris K

๐Ÿ“–

Anton

๐Ÿ› ๐Ÿ’ป ๐Ÿค” โš ๏ธ

Tim Shelburne

๐Ÿ’ป โš ๏ธ

Michaล‚ Miszczyszyn

๐Ÿ’ป

Sam K Hall

๐Ÿ’ป โš ๏ธ

Matt Jeanes

๐Ÿ’ป

Kristofer Giltvedt Selbekk

๐Ÿ’ป

Elliana May

๐Ÿ’ป โš ๏ธ

Henrik Hall

๐Ÿ’ป ๐Ÿ“–

Gregor Martynus

๐Ÿ’ป โš ๏ธ ๐Ÿ›

Sam Mesterton-Gibbons

๐Ÿ’ป ๐Ÿ› โš ๏ธ

This project follows the all-contributors specification. Contributions of any kind welcome!

Package Sidebar

Install

npm i openapi-typescript@2.3.4

Version

2.3.4

License

ISC

Unpacked Size

95.9 kB

Total Files

25

Last publish

Collaborators

  • drewpowers
  • gzm0