UNPKG

8.38 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) [![Build Status](https://travis-ci.org/YousefED/typescript-json-schema.svg?branch=master)](https://travis-ci.org/YousefED/typescript-json-schema)
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 [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([resolve("my-file.ts")], compilerOptions, basePath);
74
75// We can either get the schema for one file and one type...
76const schema = TJS.generateSchema(program, "MyType", settings);
77
78
79// ... or a generator that lets us incrementally get more schemas
80
81const generator = TJS.buildGenerator(program, settings);
82
83// all symbols
84const symbols = generator.getUserSymbols();
85
86// Get symbols for different types from generator.
87generator.getSchemaForSymbol("MyType");
88generator.getSchemaForSymbol("AnotherType");
89```
90
91```ts
92// In larger projects type names may not be unique,
93// while unique names may be enabled.
94const settings: TJS.PartialArgs = {
95 uniqueNames: true
96};
97
98const generator = TJS.buildGenerator(program, settings);
99
100// A list of all types of a given name can then be retrieved.
101const symbolList = generator.getSymbols("MyType");
102
103// Choose the appropriate type, and continue with the symbol's unique name.
104generator.getSchemaForSymbol(symbolList[1].name);
105
106// Also it is possible to get a list of all symbols.
107const fullSymbolList = generator.getSymbols();
108```
109
110`getSymbols('<SymbolName>')` and `getSymbols()` return an array of `SymbolRef`, which is of the following format:
111
112```ts
113type SymbolRef = {
114 name: string;
115 typeName: string;
116 fullyQualifiedName: string;
117 symbol: ts.Symbol;
118};
119```
120
121`getUserSymbols` and `getMainFileSymbols` return an array of `string`.
122
123### Annotations
124
125The schema generator converts annotations to JSON schema properties.
126
127For example
128
129```ts
130export interface Shape {
131 /**
132 * The size of the shape.
133 *
134 * @minimum 0
135 * @TJS-type integer
136 */
137 size: number;
138}
139```
140
141will be translated to
142
143```json
144{
145 "$ref": "#/definitions/Shape",
146 "$schema": "http://json-schema.org/draft-07/schema#",
147 "definitions": {
148 "Shape": {
149 "properties": {
150 "size": {
151 "description": "The size of the shape.",
152 "minimum": 0,
153 "type": "integer"
154 }
155 },
156 "type": "object"
157 }
158 }
159}
160```
161
162Note 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).
163
164You can also override the type of array items, either listing each field in its own annotation or one
165annotation with the full JSON of the spec (for special cases). This replaces the item types that would
166have been inferred from the TypeScript type of the array elements.
167
168Example:
169
170```ts
171export interface ShapesData {
172 /**
173 * Specify individual fields in items.
174 *
175 * @items.type integer
176 * @items.minimum 0
177 */
178 sizes: number[];
179
180 /**
181 * Or specify a JSON spec:
182 *
183 * @items {"type":"string","format":"email"}
184 */
185 emails: string[];
186}
187```
188
189Translation:
190
191```json
192{
193 "$ref": "#/definitions/ShapesData",
194 "$schema": "http://json-schema.org/draft-07/schema#",
195 "definitions": {
196 "Shape": {
197 "properties": {
198 "sizes": {
199 "description": "Specify individual fields in items.",
200 "items": {
201 "minimum": 0,
202 "type": "integer"
203 },
204 "type": "array"
205 },
206 "emails": {
207 "description": "Specify individual fields in items.",
208 "items": {
209 "format": "email",
210 "type": "string"
211 },
212 "type": "array"
213 }
214 },
215 "type": "object"
216 }
217 }
218}
219```
220
221This same syntax can be used for `contains` and `additionalProperties`.
222
223## Background
224
225Inspired 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).
226
227## Debugging
228
229`npm run debug -- test/programs/type-alias-single/main.ts --aliasRefs true MyString`
230
231And connect via the debugger protocol.