14.0.0 • Published 7 days ago

json-schema-to-typescript v14.0.0

Weekly downloads
131,587
License
MIT
Repository
github
Last release
7 days ago

json-schema-to-typescript Build Status npm mit

Compile json schema to typescript typings

Example

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

# Using Yarn:
yarn add json-schema-to-typescript

# Or, using NPM:
npm install json-schema-to-typescript --save

Usage

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):

keytypedefaultdescription
additionalPropertiesbooleantrueDefault value for additionalProperties, when it is not explicitly set
bannerCommentstring"/* 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 JSONSchema file,\n* and run json-schema-to-typescript to regenerate this file.\n*/"Disclaimer comment prepended to the top of each generated file
cwdstringprocess.cwd()Root directory for resolving $refs
declareExternallyReferencedbooleantrueDeclare external schemas referenced via $ref?
enableConstEnumsbooleantruePrepend enums with const?
formatbooleantrueFormat code? Set this to false to improve performance.
ignoreMinAndMaxItemsbooleanfalseIgnore maxItems and minItems for array types, preventing tuples being generated.
maxItemsnumber20Maximum 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.
strictIndexSignaturesbooleanfalseAppend all index signatures with \| undefined so that they are strictly typed.
styleobject{ bracketSpacing: false, printWidth: 120, semi: true, singleQuote: false, tabWidth: 2, trailingComma: 'none', useTabs: false }A Prettier configuration
unknownAnybooleantrueUse unknown instead of any where possible
unreachableDefinitionsbooleanfalseGenerates code for $defs that aren't referenced by the schema.
$refOptionsobject{}$RefParser Options, used when resolving $refs

CLI

A CLI utility is provided with this package.

cat foo.json | json2ts > foo.d.ts
# or
json2ts foo.json > foo.d.ts
# or
json2ts foo.json 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 above (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

Tests

npm test

Features

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

@boundlessdigital/meraki-dashboard-apiapi-generator-ciautumndb@knapsack/applcars-schematicsbb-frameworkboa-common-tslec-scanningconsumer-be@pureclouddev/server-apigeneratorgenerator-express-microservicepeckertestpeckertsy3tapi-transfer-codeapi-transfer-code1api-transfer-code5json-schema-ts-fastify@ldsgy/schemawinmodel-validator-tszx-ccc@bpinternal/cli@infinitebrahmanuniverse/nolb-json-s@everything-registry/sub-chunk-1985@ryanke/openapi-typescriptomanustandardmodelszodtyping@fruster/rest-client-generator@fuma-docs/openapiywapi2tsytt-promptytt-rui@geminate/yapi-to-typescript@getinsomnia/api-clientvv-yapi-to-typescriptycapi-to-typescripty2ty2t-ldapy2t-vsy2txyaml-to-analyticsyfeapi2tstypetethertzuyuyapi-autoapiyapi-plugin-cw-typescriptyapi-plugin-response-to-tsyapi-magicyapi-toyapi-to-apiyapi-to-tsyapi-to-typescriptyapi-to-typescript-testyapi-ts-cliyapi2interfaceyapi-qybyapitypeyp-custom-yapiyp-yapi@goldstack/utils-json-to-ts@gochewy/lib@halkeye/content-type-to-typescriptgenerate-react-sdkfireboom-wundersdktyrextypify-eslint-rulestypeschemagenvanced-cliutransfer-cli-demo@witheslint/generate-dtswygininc@jupytercad/schema@jxa/sdef-to-dts@jtoolkit/schema@kairan.huang/api-generator@karmic/core@karrotframe/pathfinderfastify-schema-to-typescriptfastify-schema-to-typescript-nextfaudafastify-extract-definitionsfastmode@lifeomic/one-schema@lad-tech/nsc-clifigure-clifigure-config@lord_ts/schema@hurx/core@nowak-ds/api-type-formatterglue-cligltf-typescript-generator@nu-art/schema-to-types@mojule/entity-schema@monokle/plugin-toolkitgraphql-to-config-schemagpgfs-model@octalmage/terra-cosmwasm-typescript-gen@open-kappa/myscriptsfumadocs-openapifugitiusto@microsoft/iot-cardboard-js
14.0.0

7 days ago

13.1.2

3 months ago

13.1.1

8 months ago

13.1.0

8 months ago

13.0.2

11 months ago

13.0.0

12 months ago

13.0.1

12 months ago

12.0.0

1 year ago

11.0.4

1 year ago

11.0.5

1 year ago

11.0.3

1 year ago

11.0.2

2 years ago

11.0.0

2 years ago

11.0.1

2 years ago

10.1.5

3 years ago

10.1.4

3 years ago

10.1.3

3 years ago

10.1.2

3 years ago

10.1.1

3 years ago

10.1.0

3 years ago

10.0.3

3 years ago

10.0.2

3 years ago

10.0.1

3 years ago

10.0.0

3 years ago

9.1.1

4 years ago

9.1.0

4 years ago

9.0.1

4 years ago

9.0.0

4 years ago

8.2.0

4 years ago

8.1.0

4 years ago

8.0.1

4 years ago

8.0.0

4 years ago

7.1.0

5 years ago

7.0.0

5 years ago

6.1.3

5 years ago

6.1.2

5 years ago

6.1.1

5 years ago

6.1.0

5 years ago

6.0.2

5 years ago

6.0.1

6 years ago

6.0.0

6 years ago

5.7.0

6 years ago

5.6.0

6 years ago

5.4.1

6 years ago

5.5.0

6 years ago

5.4.0

6 years ago

5.3.4

6 years ago

5.3.3

6 years ago

5.3.2

6 years ago

5.3.1

6 years ago

5.3.0

6 years ago

5.2.2

6 years ago

5.2.1

6 years ago

5.2.0

6 years ago

5.1.0

6 years ago

5.0.1

6 years ago

5.0.0

6 years ago

4.6.5

7 years ago

4.6.4

7 years ago

4.6.3

7 years ago

4.6.2

7 years ago

4.6.1

7 years ago

4.6.0

7 years ago

4.5.3

7 years ago

4.5.2

7 years ago

4.5.1

7 years ago

4.5.0

7 years ago

4.4.1

7 years ago

4.4.0

7 years ago

4.3.3

7 years ago

4.3.2

7 years ago

4.3.1

7 years ago

4.3.0

7 years ago

4.2.1

7 years ago

4.2.0

7 years ago

4.1.5

7 years ago

4.1.4

7 years ago

4.1.3

7 years ago

4.1.2

7 years ago

4.1.1

7 years ago

4.1.0

7 years ago

4.0.0

7 years ago

3.1.4

7 years ago

3.1.3

7 years ago

3.1.1

7 years ago

3.1.0

7 years ago

3.0.0

8 years ago

2.4.2

8 years ago

2.4.1

8 years ago

2.4.0

8 years ago

2.3.1

8 years ago

2.2.0

8 years ago

2.1.2

8 years ago

2.1.1

8 years ago

2.1.0

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.2.2

8 years ago

1.2.1

8 years ago

1.2.0

8 years ago

1.1.1

8 years ago

1.1.0

8 years ago

1.0.0

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago