UNPKG

11.3 kBMarkdownView Raw
1# json-schema-to-typescript [![Build Status][build]](https://github.com/bcherny/json-schema-to-typescript/actions?query=branch%3Amaster+workflow%3ACI) [![npm]](https://www.npmjs.com/package/json-schema-to-typescript) [![mit]](https://opensource.org/licenses/MIT) ![node]
2
3[build]: https://img.shields.io/github/actions/workflow/status/bcherny/json-schema-to-typescript/ci.yml?style=flat-square
4[npm]: https://img.shields.io/npm/v/json-schema-to-typescript.svg?style=flat-square
5[mit]: https://img.shields.io/npm/l/json-schema-to-typescript.svg?style=flat-square
6[node]: https://img.shields.io/badge/Node.js-16+-417e37?style=flat-square
7
8> Compile JSON Schema to TypeScript typings.
9
10## Example
11
12Check out the [live demo](https://borischerny.com/json-schema-to-typescript-browser/).
13
14Input:
15
16```json
17{
18 "title": "Example Schema",
19 "type": "object",
20 "properties": {
21 "firstName": {
22 "type": "string"
23 },
24 "lastName": {
25 "type": "string"
26 },
27 "age": {
28 "description": "Age in years",
29 "type": "integer",
30 "minimum": 0
31 },
32 "hairColor": {
33 "enum": ["black", "brown", "blue"],
34 "type": "string"
35 }
36 },
37 "additionalProperties": false,
38 "required": ["firstName", "lastName"]
39}
40```
41
42Output:
43
44```ts
45export interface ExampleSchema {
46 firstName: string;
47 lastName: string;
48 /**
49 * Age in years
50 */
51 age?: number;
52 hairColor?: "black" | "brown" | "blue";
53}
54```
55
56## Installation
57
58```sh
59npm install json-schema-to-typescript
60```
61
62## Usage
63
64json-schema-to-typescript is easy to use via the CLI, or programmatically.
65
66### CLI
67
68First make the CLI available using one of the following options:
69
70```sh
71# install locally, then use `npx json2ts`
72npm install json-schema-to-typescript
73
74# or install globally, then use `json2ts`
75npm install json-schema-to-typescript --global
76
77# or install to npm cache, then use `npx --package=json-schema-to-typescript json2ts`
78# (you don't need to run an install command first)
79```
80
81Then, use the CLI to convert JSON files to TypeScript typings:
82
83```sh
84cat foo.json | json2ts > foo.d.ts
85# or
86json2ts foo.json > foo.d.ts
87# or
88json2ts foo.yaml foo.d.ts
89# or
90json2ts --input foo.json --output foo.d.ts
91# or
92json2ts -i foo.json -o foo.d.ts
93# or (quote globs so that your shell doesn't expand them)
94json2ts -i 'schemas/**/*.json'
95# or
96json2ts -i schemas/ -o types/
97```
98
99You 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.
100
101```sh
102# generate code for definitions that aren't referenced
103json2ts -i foo.json -o foo.d.ts --unreachableDefinitions
104# use single quotes and disable trailing semicolons
105json2ts -i foo.json -o foo.d.ts --style.singleQuote --no-style.semi
106```
107
108### API
109
110To invoke json-schema-to-typescript from your TypeScript or JavaScript program, import it and call `compile` or `compileFromFile`.
111
112```js
113import { compile, compileFromFile } from 'json-schema-to-typescript'
114
115// compile from file
116compileFromFile('foo.json')
117 .then(ts => fs.writeFileSync('foo.d.ts', ts))
118
119// or, compile a JS object
120let mySchema = {
121 properties: [...]
122}
123compile(mySchema, 'MySchema')
124 .then(ts => ...)
125```
126
127See [server demo](example) and [browser demo](https://github.com/bcherny/json-schema-to-typescript-browser) for full examples.
128
129## Options
130
131`compileFromFile` and `compile` accept options as their last argument (all keys are optional):
132
133| key | type | default | description |
134|-|-|-|-|
135| additionalProperties | boolean | `true` | Default value for `additionalProperties`, when it is not explicitly set |
136| 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 |
137| customName | `(LinkedJSONSchema, string \| undefined) => string \| undefined` | `undefined` | Custom function to provide a type name for a given schema
138| cwd | string | `process.cwd()` | Root directory for resolving [`$ref`](https://tools.ietf.org/id/draft-pbryan-zyp-json-ref-03.html)s |
139| declareExternallyReferenced | boolean | `true` | Declare external schemas referenced via `$ref`? |
140| enableConstEnums | boolean | `true` | Prepend enums with [`const`](https://www.typescriptlang.org/docs/handbook/enums.html#computed-and-constant-members)? |
141| inferStringEnumKeysFromValues | boolean | `false` | Create enums from JSON enums with eponymous keys |
142| format | boolean | `true` | Format code? Set this to `false` to improve performance. |
143| ignoreMinAndMaxItems | boolean | `false` | Ignore maxItems and minItems for `array` types, preventing tuples being generated. |
144| 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`.
145| strictIndexSignatures | boolean | `false` | Append all index signatures with `\| undefined` so that they are strictly typed. |
146| style | object | `{ bracketSpacing: false, printWidth: 120, semi: true, singleQuote: false, tabWidth: 2, trailingComma: 'none', useTabs: false }` | A [Prettier](https://prettier.io/docs/en/options.html) configuration |
147| unknownAny | boolean | `true` | Use `unknown` instead of `any` where possible |
148| unreachableDefinitions | boolean | `false` | Generates code for `$defs` that aren't referenced by the schema. |
149| $refOptions | object | `{}` | [$RefParser](https://github.com/APIDevTools/json-schema-ref-parser) Options, used when resolving `$ref`s |
150
151## Tests
152
153```sh
154$ npm test
155```
156
157## Features
158
159- [x] `title` => `interface`
160- [x] Primitive types:
161 - [x] array
162 - [x] homogeneous array
163 - [x] boolean
164 - [x] integer
165 - [x] number
166 - [x] null
167 - [x] object
168 - [x] string
169 - [x] homogeneous enum
170 - [x] heterogeneous enum
171- [x] Non/extensible interfaces
172- [ ] Custom JSON-schema extensions
173- [x] Nested properties
174- [x] Schema definitions
175- [x] [Schema references](http://json-schema.org/latest/json-schema-core.html#rfc.section.7.2.2)
176- [x] Local (filesystem) schema references
177- [x] External (network) schema references
178- [x] Add support for running in browser
179- [x] default interface name
180- [x] infer unnamed interface name from filename
181- [x] `deprecated`
182- [x] `allOf` ("intersection")
183- [x] `anyOf` ("union")
184- [x] `oneOf` (treated like `anyOf`)
185- [x] `maxItems` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L166))
186- [x] `minItems` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L165))
187- [x] `additionalProperties` of type
188- [x] `patternProperties` (partial support)
189- [x] [`extends`](https://github.com/json-schema/json-schema/wiki/Extends/014e3cd8692250baad70c361dd81f6119ad0f696)
190- [x] `required` properties on objects ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L130))
191- [ ] `validateRequired` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L124))
192- [x] literal objects in enum ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L236))
193- [x] referencing schema by id ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L331))
194- [x] custom typescript types via `tsType`
195
196## Custom schema properties:
197
198- `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](https://github.com/sokra/json-schema-to-typescript/blob/f1f40307cf5efa328522bb1c9ae0b0d9e5f367aa/test/e2e/customType.ts)).
199- `tsEnumNames`: Overrides the names used for the elements in an enum. Can also be used to create string enums ([eg](https://github.com/johnbillion/wp-json-schemas/blob/647440573e4a675f15880c95fcca513fdf7a2077/schemas/properties/post-status-name.json)).
200
201## Not expressible in TypeScript:
202
203- `dependencies` ([single](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L261), [multiple](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L282))
204- `divisibleBy` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L185))
205- [`format`](https://github.com/json-schema/json-schema/wiki/Format) ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L209))
206- `multipleOf` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L186))
207- `maximum` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L183))
208- `minimum` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L182))
209- `maxProperties` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L113))
210- `minProperties` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L112))
211- `not`/`disallow`
212- `oneOf` ("xor", use `anyOf` instead)
213- `pattern` ([string](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L203), [regex](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L207))
214- `uniqueItems` ([eg](https://github.com/tdegrunt/jsonschema/blob/67c0e27ce9542efde0bf43dc1b2a95dd87df43c3/examples/all.js#L172))
215
216## FAQ
217
218### JSON-Schema-to-TypeScript is crashing on my giant file. What can I do?
219
220Prettier is known to run slowly on really big files. To skip formatting and improve performance, set the `format` option to `false`.
221
222## Further Reading
223
224- JSON-schema spec: https://tools.ietf.org/html/draft-zyp-json-schema-04
225- JSON-schema wiki: https://github.com/json-schema/json-schema/wiki
226- JSON-schema test suite: https://github.com/json-schema/JSON-Schema-Test-Suite/blob/node
227- TypeScript spec: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md
228
229## Who uses JSON-Schema-to-TypeScript?
230
231- [Alibaba](https://github.com/alibaba/lowcode-engine)
232- [Amazon](https://github.com/aws/aws-toolkit-vscode), [AWSLabs](https://github.com/awslabs/cdk8s)
233- [Expo](https://github.com/expo/expo)
234- [FormatJS](https://github.com/formatjs/formatjs)
235- [Microsoft](https://github.com/microsoft/mixed-reality-extension-sdk)
236- [Mozilla](https://github.com/mdn/browser-compat-data)
237- [Nx](https://github.com/nrwl/nx)
238- [RStudio](https://github.com/rstudio/rstudio)
239- [Sourcegraph](https://github.com/sourcegraph/sourcegraph)
240- [Stryker](https://github.com/stryker-mutator/stryker)
241- [Webpack](https://github.com/webpack/webpack)
242- [See more](https://github.com/bcherny/json-schema-to-typescript/network/dependents?package_id=UGFja2FnZS0xNjUxOTM5Mg%3D%3D)