UNPKG

11.1 kBMarkdownView Raw
1# typescript-json-schema
2
3[![npm version](https://img.shields.io/npm/v/typescript-json-schema.svg)](https://www.npmjs.com/package/typescript-json-schema) ![Test](https://github.com/YousefED/typescript-json-schema/workflows/Test/badge.svg)
4
5Generate json-schemas from your Typescript sources.
6
7## Features
8
9- Compiles your Typescript program to get complete type information.
10- Translates required properties, extends, annotation keywords, property initializers as defaults. You can find examples for these features in the [api doc](https://github.com/YousefED/typescript-json-schema/tree/master/api.md) or the [test examples](https://github.com/YousefED/typescript-json-schema/tree/master/test/programs).
11
12## Usage
13
14### Command line
15
16- Install with `npm install typescript-json-schema -g`
17- Generate schema from a typescript type: `typescript-json-schema project/directory/tsconfig.json TYPE`
18
19To generate files for only _some_ types in `tsconfig.json` specify
20filenames or globs with the `--include` option. This is especially useful for large projects.
21
22In case no `tsconfig.json` is available for your project, you can directly specify the .ts files (this in this case we use some built-in compiler presets):
23
24- Generate schema from a typescript type: `typescript-json-schema "project/directory/**/*.ts" TYPE`
25
26The `TYPE` can either be a single, fully qualified type or `"*"` to generate the schema for all types.
27
28```
29Usage: typescript-json-schema <path-to-typescript-files-or-tsconfig> <type>
30
31Options:
32 --refs Create shared ref definitions. [boolean] [default: true]
33 --aliasRefs Create shared ref definitions for the type aliases. [boolean] [default: false]
34 --topRef Create a top-level ref definition. [boolean] [default: false]
35 --titles Creates titles in the output schema. [boolean] [default: false]
36 --defaultProps Create default properties definitions. [boolean] [default: false]
37 --noExtraProps Disable additional properties in objects by default. [boolean] [default: false]
38 --propOrder Create property order definitions. [boolean] [default: false]
39 --required Create required array for non-optional properties. [boolean] [default: false]
40 --strictNullChecks Make values non-nullable by default. [boolean] [default: false]
41 --esModuleInterop Use esModuleInterop when loading typescript modules. [boolean] [default: false]
42 --skipLibCheck Use skipLibCheck when loading typescript modules. [boolean] [default: false]
43 --useTypeOfKeyword Use `typeOf` keyword (https://goo.gl/DC6sni) for functions. [boolean] [default: false]
44 --out, -o The output file, defaults to using stdout
45 --validationKeywords Provide additional validation keywords to include [array] [default: []]
46 --include Further limit tsconfig to include only matching files [array] [default: []]
47 --ignoreErrors Generate even if the program has errors. [boolean] [default: false]
48 --excludePrivate Exclude private members from the schema [boolean] [default: false]
49 --uniqueNames Use unique names for type symbols. [boolean] [default: false]
50 --rejectDateType Rejects Date fields in type definitions. [boolean] [default: false]
51 --id Set schema id. [string] [default: ""]
52 --defaultNumberType Default number type. [choices: "number", "integer"] [default: "number"]
53 --tsNodeRegister Use ts-node/register (needed for require typescript files). [boolean] [default: false]
54 --constAsEnum Use enums with a single value when declaring constants. [boolean] [default: false]
55 --experimentalDecorators Use experimentalDecorators when loading typescript modules.
56 [boolean] [default: true]
57```
58
59### Programmatic use
60
61```ts
62import { resolve } from "path";
63
64import * as TJS from "typescript-json-schema";
65
66// optionally pass argument to schema generator
67const settings: TJS.PartialArgs = {
68 required: true,
69};
70
71// optionally pass ts compiler options
72const compilerOptions: TJS.CompilerOptions = {
73 strictNullChecks: true,
74};
75
76// optionally pass a base path
77const basePath = "./my-dir";
78
79const program = TJS.getProgramFromFiles(
80 [resolve("my-file.ts")],
81 compilerOptions,
82 basePath
83);
84
85// We can either get the schema for one file and one type...
86const schema = TJS.generateSchema(program, "MyType", settings);
87
88// ... or a generator that lets us incrementally get more schemas
89
90const generator = TJS.buildGenerator(program, settings);
91
92// generator can be also reused to speed up generating the schema if usecase allows:
93const schemaWithReusedGenerator = TJS.generateSchema(program, "MyType", settings, [], generator);
94
95// all symbols
96const symbols = generator.getUserSymbols();
97
98// Get symbols for different types from generator.
99generator.getSchemaForSymbol("MyType");
100generator.getSchemaForSymbol("AnotherType");
101```
102
103```ts
104// In larger projects type names may not be unique,
105// while unique names may be enabled.
106const settings: TJS.PartialArgs = {
107 uniqueNames: true,
108};
109
110const generator = TJS.buildGenerator(program, settings);
111
112// A list of all types of a given name can then be retrieved.
113const symbolList = generator.getSymbols("MyType");
114
115// Choose the appropriate type, and continue with the symbol's unique name.
116generator.getSchemaForSymbol(symbolList[1].name);
117
118// Also it is possible to get a list of all symbols.
119const fullSymbolList = generator.getSymbols();
120```
121
122`getSymbols('<SymbolName>')` and `getSymbols()` return an array of `SymbolRef`, which is of the following format:
123
124```ts
125type SymbolRef = {
126 name: string;
127 typeName: string;
128 fullyQualifiedName: string;
129 symbol: ts.Symbol;
130};
131```
132
133`getUserSymbols` and `getMainFileSymbols` return an array of `string`.
134
135### Annotations
136
137The schema generator converts annotations to JSON schema properties.
138
139For example
140
141```ts
142export interface Shape {
143 /**
144 * The size of the shape.
145 *
146 * @minimum 0
147 * @TJS-type integer
148 */
149 size: number;
150}
151```
152
153will be translated to
154
155```json
156{
157 "$ref": "#/definitions/Shape",
158 "$schema": "http://json-schema.org/draft-07/schema#",
159 "definitions": {
160 "Shape": {
161 "properties": {
162 "size": {
163 "description": "The size of the shape.",
164 "minimum": 0,
165 "type": "integer"
166 }
167 },
168 "type": "object"
169 }
170 }
171}
172```
173
174Note that we needed to use `@TJS-type` instead of just `@type` because of an [issue with the typescript compiler](https://github.com/Microsoft/TypeScript/issues/13498).
175
176You can also override the type of array items, either listing each field in its own annotation or one
177annotation with the full JSON of the spec (for special cases). This replaces the item types that would
178have been inferred from the TypeScript type of the array elements.
179
180Example:
181
182```ts
183export interface ShapesData {
184 /**
185 * Specify individual fields in items.
186 *
187 * @items.type integer
188 * @items.minimum 0
189 */
190 sizes: number[];
191
192 /**
193 * Or specify a JSON spec:
194 *
195 * @items {"type":"string","format":"email"}
196 */
197 emails: string[];
198}
199```
200
201Translation:
202
203```json
204{
205 "$ref": "#/definitions/ShapesData",
206 "$schema": "http://json-schema.org/draft-07/schema#",
207 "definitions": {
208 "Shape": {
209 "properties": {
210 "sizes": {
211 "description": "Specify individual fields in items.",
212 "items": {
213 "minimum": 0,
214 "type": "integer"
215 },
216 "type": "array"
217 },
218 "emails": {
219 "description": "Or specify a JSON spec:",
220 "items": {
221 "format": "email",
222 "type": "string"
223 },
224 "type": "array"
225 }
226 },
227 "type": "object"
228 }
229 }
230}
231```
232
233This same syntax can be used for `contains` and `additionalProperties`.
234
235### `integer` type alias
236
237If you create a type alias `integer` for `number` it will be mapped to the `integer` type in the generated JSON schema.
238
239Example:
240
241```typescript
242type integer = number;
243interface MyObject {
244 n: integer;
245}
246```
247
248Note: this feature doesn't work for generic types & array types, it mainly works in very simple cases.
249
250### `require` a variable from a file
251
252(for requiring typescript files is needed to set argument `tsNodeRegister` to true)
253
254When you want to import for example an object or an array into your property defined in annotation, you can use `require`.
255
256Example:
257
258```ts
259export interface InnerData {
260 age: number;
261 name: string;
262 free: boolean;
263}
264
265export interface UserData {
266 /**
267 * Specify required object
268 *
269 * @examples require("./example.ts").example
270 */
271 data: InnerData;
272}
273```
274
275file `example.ts`
276
277```ts
278export const example: InnerData[] = [{
279 age: 30,
280 name: "Ben",
281 free: false
282}]
283```
284
285Translation:
286
287```json
288{
289 "$schema": "http://json-schema.org/draft-07/schema#",
290 "properties": {
291 "data": {
292 "description": "Specify required object",
293 "examples": [
294 {
295 "age": 30,
296 "name": "Ben",
297 "free": false
298 }
299 ],
300 "type": "object",
301 "properties": {
302 "age": { "type": "number" },
303 "name": { "type": "string" },
304 "free": { "type": "boolean" }
305 },
306 "required": ["age", "free", "name"]
307 }
308 },
309 "required": ["data"],
310 "type": "object"
311}
312```
313
314Also you can use `require(".").example`, which will try to find exported variable with name 'example' in current file. Or you can use `require("./someFile.ts")`, which will try to use default exported variable from 'someFile.ts'.
315
316Note: For `examples` a required variable must be an array.
317
318## Background
319
320Inspired and builds upon [Typson](https://github.com/lbovet/typson/), but typescript-json-schema is compatible with more recent Typescript versions. Also, since it uses the Typescript compiler internally, more advanced scenarios are possible. If you are looking for a library that uses the AST instead of the type hierarchy and therefore better support for type aliases, have a look at [vega/ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator).
321
322## Debugging
323
324`npm run debug -- test/programs/type-alias-single/main.ts --aliasRefs true MyString`
325
326And connect via the debugger protocol.