UNPKG

8.43 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 --useTypeOfKeyword Use `typeOf` keyword (https://goo.gl/DC6sni) for functions. [boolean] [default: false]
42 --out, -o The output file, defaults to using stdout
43 --validationKeywords Provide additional validation keywords to include [array] [default: []]
44 --include Further limit tsconfig to include only matching files [array] [default: []]
45 --ignoreErrors Generate even if the program has errors. [boolean] [default: false]
46 --excludePrivate Exclude private members from the schema [boolean] [default: false]
47 --uniqueNames Use unique names for type symbols. [boolean] [default: false]
48 --rejectDateType Rejects Date fields in type definitions. [boolean] [default: false]
49 --id Set schema id. [string] [default: ""]
50 --defaultNumberType Default number type. [choices: "number", "integer"] [default: "number"]
51```
52
53### Programmatic use
54
55```ts
56import { resolve } from "path";
57
58import * as TJS from "typescript-json-schema";
59
60// optionally pass argument to schema generator
61const settings: TJS.PartialArgs = {
62 required: true,
63};
64
65// optionally pass ts compiler options
66const compilerOptions: TJS.CompilerOptions = {
67 strictNullChecks: true,
68};
69
70// optionally pass a base path
71const basePath = "./my-dir";
72
73const program = TJS.getProgramFromFiles(
74 [resolve("my-file.ts")],
75 compilerOptions,
76 basePath
77);
78
79// We can either get the schema for one file and one type...
80const schema = TJS.generateSchema(program, "MyType", settings);
81
82// ... or a generator that lets us incrementally get more schemas
83
84const generator = TJS.buildGenerator(program, settings);
85
86// all symbols
87const symbols = generator.getUserSymbols();
88
89// Get symbols for different types from generator.
90generator.getSchemaForSymbol("MyType");
91generator.getSchemaForSymbol("AnotherType");
92```
93
94```ts
95// In larger projects type names may not be unique,
96// while unique names may be enabled.
97const settings: TJS.PartialArgs = {
98 uniqueNames: true,
99};
100
101const generator = TJS.buildGenerator(program, settings);
102
103// A list of all types of a given name can then be retrieved.
104const symbolList = generator.getSymbols("MyType");
105
106// Choose the appropriate type, and continue with the symbol's unique name.
107generator.getSchemaForSymbol(symbolList[1].name);
108
109// Also it is possible to get a list of all symbols.
110const fullSymbolList = generator.getSymbols();
111```
112
113`getSymbols('<SymbolName>')` and `getSymbols()` return an array of `SymbolRef`, which is of the following format:
114
115```ts
116type SymbolRef = {
117 name: string;
118 typeName: string;
119 fullyQualifiedName: string;
120 symbol: ts.Symbol;
121};
122```
123
124`getUserSymbols` and `getMainFileSymbols` return an array of `string`.
125
126### Annotations
127
128The schema generator converts annotations to JSON schema properties.
129
130For example
131
132```ts
133export interface Shape {
134 /**
135 * The size of the shape.
136 *
137 * @minimum 0
138 * @TJS-type integer
139 */
140 size: number;
141}
142```
143
144will be translated to
145
146```json
147{
148 "$ref": "#/definitions/Shape",
149 "$schema": "http://json-schema.org/draft-07/schema#",
150 "definitions": {
151 "Shape": {
152 "properties": {
153 "size": {
154 "description": "The size of the shape.",
155 "minimum": 0,
156 "type": "integer"
157 }
158 },
159 "type": "object"
160 }
161 }
162}
163```
164
165Note 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).
166
167You can also override the type of array items, either listing each field in its own annotation or one
168annotation with the full JSON of the spec (for special cases). This replaces the item types that would
169have been inferred from the TypeScript type of the array elements.
170
171Example:
172
173```ts
174export interface ShapesData {
175 /**
176 * Specify individual fields in items.
177 *
178 * @items.type integer
179 * @items.minimum 0
180 */
181 sizes: number[];
182
183 /**
184 * Or specify a JSON spec:
185 *
186 * @items {"type":"string","format":"email"}
187 */
188 emails: string[];
189}
190```
191
192Translation:
193
194```json
195{
196 "$ref": "#/definitions/ShapesData",
197 "$schema": "http://json-schema.org/draft-07/schema#",
198 "definitions": {
199 "Shape": {
200 "properties": {
201 "sizes": {
202 "description": "Specify individual fields in items.",
203 "items": {
204 "minimum": 0,
205 "type": "integer"
206 },
207 "type": "array"
208 },
209 "emails": {
210 "description": "Or specify a JSON spec:",
211 "items": {
212 "format": "email",
213 "type": "string"
214 },
215 "type": "array"
216 }
217 },
218 "type": "object"
219 }
220 }
221}
222```
223
224This same syntax can be used for `contains` and `additionalProperties`.
225
226### `integer` type alias
227
228If you create a type alias `integer` for `number` it will be mapped to the `integer` type in the generated JSON schema.
229
230Example:
231
232```typescript
233type integer = number;
234interface MyObject {
235 n: integer;
236}
237```
238
239Note: this feature doesn't work for generic types & array types, it mainly works in very simple cases.
240
241## Background
242
243Inspired 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).
244
245## Debugging
246
247`npm run debug -- test/programs/type-alias-single/main.ts --aliasRefs true MyString`
248
249And connect via the debugger protocol.