UNPKG

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