Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

json-schema-to-typescript

bcherny1.8mMIT15.0.4TypeScript support: included

compile json schema to typescript typings

json, schema, typescript, compile, transpile, api, interface, typing, share

readme

json-schema-to-typescript Build Status npm mit node

Compile JSON Schema to TypeScript typings.

Example

Check out the live demo.

Input:

{
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "string"
    },
    "age": {
      "description": "Age in years",
      "type": "integer",
      "minimum": 0
    },
    "hairColor": {
      "enum": ["black", "brown", "blue"],
      "type": "string"
    }
  },
  "additionalProperties": false,
  "required": ["firstName", "lastName"]
}

Output:

export interface ExampleSchema {
  firstName: string;
  lastName: string;
  /**
   * Age in years
   */
  age?: number;
  hairColor?: "black" | "brown" | "blue";
}

Installation

npm install json-schema-to-typescript

Usage

json-schema-to-typescript is easy to use via the CLI, or programmatically.

CLI

First make the CLI available using one of the following options:

# install locally, then use `npx json2ts`
npm install json-schema-to-typescript

# or install globally, then use `json2ts`
npm install json-schema-to-typescript --global

# or install to npm cache, then use `npx --package=json-schema-to-typescript json2ts`
# (you don't need to run an install command first)

Then, use the CLI to convert JSON files to TypeScript typings:

cat foo.json | json2ts > foo.d.ts
# or
json2ts foo.json > foo.d.ts
# or
json2ts foo.yaml foo.d.ts
# or
json2ts --input foo.json --output foo.d.ts
# or
json2ts -i foo.json -o foo.d.ts
# or (quote globs so that your shell doesn't expand them)
json2ts -i 'schemas/**/*.json'
# or
json2ts -i schemas/ -o types/

You can pass any of the options described below (including style options) as CLI flags. Boolean values can be set to false using the no- prefix.

# generate code for definitions that aren't referenced
json2ts -i foo.json -o foo.d.ts --unreachableDefinitions
# use single quotes and disable trailing semicolons
json2ts -i foo.json -o foo.d.ts --style.singleQuote --no-style.semi

API

To invoke json-schema-to-typescript from your TypeScript or JavaScript program, import it and call compile or compileFromFile.

import { compile, compileFromFile } from 'json-schema-to-typescript'

// compile from file
compileFromFile('foo.json')
  .then(ts => fs.writeFileSync('foo.d.ts', ts))

// or, compile a JS object
let mySchema = {
  properties: [...]
}
compile(mySchema, 'MySchema')
  .then(ts => ...)

See server demo and browser demo for full examples.

Options

compileFromFile and compile accept options as their last argument (all keys are optional):

key type default description
additionalProperties boolean true Default value for additionalProperties, when it is not explicitly set
bannerComment string "/* eslint-disable */\n/**\n* This file was automatically generated by json-schema-to-typescript.\n* DO NOT MODIFY IT BY HAND. Instead, modify the source JSON Schema file,\n* and run json-schema-to-typescript to regenerate this file.\n*/" Disclaimer comment prepended to the top of each generated file
customName (LinkedJSONSchema, string | undefined) => string | undefined undefined Custom function to provide a type name for a given schema
cwd string process.cwd() Root directory for resolving $refs
declareExternallyReferenced boolean true Declare external schemas referenced via $ref?
enableConstEnums boolean true Prepend enums with const?
inferStringEnumKeysFromValues boolean false Create enums from JSON enums with eponymous keys
format boolean true Format code? Set this to false to improve performance.
ignoreMinAndMaxItems boolean false Ignore maxItems and minItems for array types, preventing tuples being generated.
maxItems number 20 Maximum number of unioned tuples to emit when representing bounded-size array types, before falling back to emitting unbounded arrays. Increase this to improve precision of emitted types, decrease it to improve performance, or set it to -1 to ignore maxItems.
strictIndexSignatures boolean false Append all index signatures with | undefined so that they are strictly typed.
style object { bracketSpacing: false, printWidth: 120, semi: true, singleQuote: false, tabWidth: 2, trailingComma: 'none', useTabs: false } A Prettier configuration
unknownAny boolean true Use unknown instead of any where possible
unreachableDefinitions boolean false Generates code for $defs that aren't referenced by the schema.
$refOptions object {} $RefParser Options, used when resolving $refs

Tests

$ npm test

Features

  • <input checked="" disabled="" type="checkbox"> title => interface
  • <input checked="" disabled="" type="checkbox"> Primitive types:
    • <input checked="" disabled="" type="checkbox"> array
    • <input checked="" disabled="" type="checkbox"> homogeneous array
    • <input checked="" disabled="" type="checkbox"> boolean
    • <input checked="" disabled="" type="checkbox"> integer
    • <input checked="" disabled="" type="checkbox"> number
    • <input checked="" disabled="" type="checkbox"> null
    • <input checked="" disabled="" type="checkbox"> object
    • <input checked="" disabled="" type="checkbox"> string
    • <input checked="" disabled="" type="checkbox"> homogeneous enum
    • <input checked="" disabled="" type="checkbox"> heterogeneous enum
  • <input checked="" disabled="" type="checkbox"> Non/extensible interfaces
  • <input disabled="" type="checkbox"> Custom JSON-schema extensions
  • <input checked="" disabled="" type="checkbox"> Nested properties
  • <input checked="" disabled="" type="checkbox"> Schema definitions
  • <input checked="" disabled="" type="checkbox"> Schema references
  • <input checked="" disabled="" type="checkbox"> Local (filesystem) schema references
  • <input checked="" disabled="" type="checkbox"> External (network) schema references
  • <input checked="" disabled="" type="checkbox"> Add support for running in browser
  • <input checked="" disabled="" type="checkbox"> default interface name
  • <input checked="" disabled="" type="checkbox"> infer unnamed interface name from filename
  • <input checked="" disabled="" type="checkbox"> deprecated
  • <input checked="" disabled="" type="checkbox"> allOf ("intersection")
  • <input checked="" disabled="" type="checkbox"> anyOf ("union")
  • <input checked="" disabled="" type="checkbox"> oneOf (treated like anyOf)
  • <input checked="" disabled="" type="checkbox"> maxItems (eg)
  • <input checked="" disabled="" type="checkbox"> minItems (eg)
  • <input checked="" disabled="" type="checkbox"> additionalProperties of type
  • <input checked="" disabled="" type="checkbox"> patternProperties (partial support)
  • <input checked="" disabled="" type="checkbox"> extends
  • <input checked="" disabled="" type="checkbox"> required properties on objects (eg)
  • <input disabled="" type="checkbox"> validateRequired (eg)
  • <input checked="" disabled="" type="checkbox"> literal objects in enum (eg)
  • <input checked="" disabled="" type="checkbox"> referencing schema by id (eg)
  • <input checked="" disabled="" type="checkbox"> custom typescript types via tsType

Custom schema properties:

  • tsType: Overrides the type that's generated from the schema. Useful for forcing a type to any or when using non-standard JSON schema extensions (eg).
  • tsEnumNames: Overrides the names used for the elements in an enum. Can also be used to create string enums (eg).

Not expressible in TypeScript:

FAQ

JSON-Schema-to-TypeScript is crashing on my giant file. What can I do?

Prettier is known to run slowly on really big files. To skip formatting and improve performance, set the format option to false.

Further Reading

Who uses JSON-Schema-to-TypeScript?

changelog

Changelog

*Note: This is a partial changelog, covering significant & breaking changes. For a full list of changes, please consult the commit log.

15.0.0

  • 62cc052 Fixed bug where intersection schemas didn't generate complete types. Improved output readability for intersection types (#603)

14.1.0

  • 3e2e1e9 Added inferStringEnumKeysFromValues option (#578)

14.0.5

  • b7fee29 Added .yaml support for CLI (#598)

14.0.2

  • 9ec0c70 Added .yaml support (#577)

14.0.1

  • 2f29f19 Added customName option

14.0.0

  • 967eb13 Require Node v16+

13.1.0

  • f797848 Feat: Add support for deprecated keyword

13.0.1

  • b13a6f2 Bugfix: Boolean CLI flags were not respected (#524)

13.0.0

  • 05b0103 Bugfix: Parse boolean schemas as schemas, rather than as literals (#515)
  • 8f973d1 Bugfix: Fix edge case where emitted names were corrupted when using strictIndexSignature (#423)

12.0.0

  • b73e1c7 Bugfix: Parse enums as literals, rather than as schemas (#508)

11.0.0

This is a major release with lots of bugfixes, some of which may change emitted types.

  • 2ca6e50 Bugfix: Fix crash that may happen when emitting types for cyclical schemas (#323, #376)
  • 8fa728e Bugfix: Fix tests on Windows, make snapshot ordering consistent
  • b78a616 Bugfix: Make compile() non-mutating (#370, #443)
  • a89ffe1 Bugfix: Add maximum size heuristic for tuple types (#438)
  • 6fbcbc8 Bugfix: Improve performance & stability issue caused by JSON serialization (#422)
  • 7aa353d Feat: Add support for $id (#436)
  • 59747b1 Feat: Add support for specifying a default for additionalProperties (#335)
  • 966cca5 Cleanup: Drop support for Node 10

10.1.0

  • ec78099 Feat: Add support for JSON Schema const and $defs keywords (#263)

10.0.0

Lots of bugfixes, some of which may be breaking changes.

  • 4aabd23 Bugfix: Correctly generate intersection types when a schema combines multiple JSON Schema directives (eg. properties and allOf) (#157, #243, #256, #314)
  • 3a45990 Bugfix: Referenced schemas are now correctly normalized, improving emitted type declarations for some kinds of referenced schemas with properies using minItems or maxItems
  • 800c076 1ec105d Bugfix: Fix bugs where complex unions were partially emitted in some cases (#277, #320, #326, #327)
  • 828cc05 Bugfix: Fixed an issue where enum names were sometimes incorrectly generated (#339)
  • e038017 Bugfix: Fixed an issue where union member names and comments were incorrect or omitted in some cases (#329)
  • 2b406f9 Bugfix: Fixed an issue where base types were not deduped before emission when using extends (#322)
  • 47036f5 ba4aa65 Perf: Significant performance improvements

9.1.0

  • d88a514 Bugfix: Improve deduping logic for anyOf (#273)
  • 8f3f101 Bugfix: Multiple fixes for CLI
  • d0ad44b Perf: Improve normalizer performance (#286)

9.0.0

This release brings improved typesafety, thorough testing of all supported NodeJS version and operating systems on CI, and bugfixes.

  • 105d239 Feat: Emit unknown instead of any by default
  • 8f0b1bc Feat: Add unknownAny CLI option (#281)
  • 375dfd2 Bugfix: Fix generated type names to increment counters, instead of appending when we're unable to infer a type's name
  • 7f52f98 Drop support for NodeJS <10

8.2.0

  • a0257d8 Feat: Add support for directories and globs as inputs (#238)

8.1.0

  • 1d24618 Feat: Add ignoreMinAndMaxItems CLI option, defaulting to false (#274)

8.0.0

  • e144890 Bugfix: Improve generated output when mixing nulls and unions (#261)

7.1.0

  • ddbd627 Feat: Add strictIndexSignatures CLI option, defaulting to false (#252)

7.0.0

  • b9c4bcb Feat: Add support for additionalItems for tuple types
  • c5f4f03 Feat: Add support for minItems and maxItems

6.1.0

  • 57f759f Feat: Add @tslint directive to disable linting for generated files by default (#192)

6.0.0

  • b7737b7 Bugfix: Improve generated type & interface names to take input casing into account (#159)

5.7.0

  • f1f4030 Feat: Add tsType schema extension to allow custom TypeScript types (#168)
  • 8599262 Feat: Add support for passing custom options when resolving $refs (#180)
  • 25ef03b Feat: Improve error output for certain kinds of errors (#188)

5.6.0

  • 923dbfc Feat: Add declarations for tuple types (#184)

5.4.0

  • fc8540f Feat: Add partial support for patternProperties
  • 9167902 Feat: Add declarations for enums referenced by arrays (#146)

5.3.0

  • 83e4a29 Feat: Add support for passing options in CLI

5.2.0

  • 9187237 Feat: Add support for generating typings from definitions that are not directly referenced by a schema (#133)
  • 7d864b9 Feat: Add support for generating typings from patternProperties (#124)

5.0.0