typescript-json-schema

Generate json-schema from your Typescript sources

README

typescript-json-schema

npm version Test

Generate json-schemas from your Typescript sources.

Features


- Compiles your Typescript program to get complete type information.
- Translates required properties, extends, annotation keywords, property initializers as defaults. You can find examples for these features in the api doc or the test examples.

Usage


Command line


- Install with npm install typescript-json-schema -g
- Generate schema from a typescript type: typescript-json-schema project/directory/tsconfig.json TYPE

To generate files for only _some_ types in tsconfig.json specify
filenames or globs with the --include option. This is especially useful for large projects.

In 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):

- Generate schema from a typescript type: `typescript-json-schema "project/directory/*/.ts" TYPE`

The TYPE can either be a single, fully qualified type or "*" to generate the schema for all types.

  1. ```
  2. Usage: typescript-json-schema <path-to-typescript-files-or-tsconfig> <type>

  3. Options:
  4.   --refs                Create shared ref definitions.                               [boolean] [default: true]
  5.   --aliasRefs           Create shared ref definitions for the type aliases.          [boolean] [default: false]
  6.   --topRef              Create a top-level ref definition.                           [boolean] [default: false]
  7.   --titles              Creates titles in the output schema.                         [boolean] [default: false]
  8.   --defaultProps        Create default properties definitions.                       [boolean] [default: false]
  9.   --noExtraProps        Disable additional properties in objects by default.         [boolean] [default: false]
  10.   --propOrder           Create property order definitions.                           [boolean] [default: false]
  11.   --required            Create required array for non-optional properties.           [boolean] [default: false]
  12.   --strictNullChecks    Make values non-nullable by default.                         [boolean] [default: false]
  13.   --esModuleInterop     Use esModuleInterop when loading typescript modules.         [boolean] [default: false]
  14.   --useTypeOfKeyword    Use `typeOf` keyword (https://goo.gl/DC6sni) for functions.  [boolean] [default: false]
  15.   --out, -o             The output file, defaults to using stdout
  16.   --validationKeywords  Provide additional validation keywords to include            [array]   [default: []]
  17.   --include             Further limit tsconfig to include only matching files        [array]   [default: []]
  18.   --ignoreErrors        Generate even if the program has errors.                     [boolean] [default: false]
  19.   --excludePrivate      Exclude private members from the schema                      [boolean] [default: false]
  20.   --uniqueNames         Use unique names for type symbols.                           [boolean] [default: false]
  21.   --rejectDateType      Rejects Date fields in type definitions.                     [boolean] [default: false]
  22.   --id                  Set schema id.                                               [string]  [default: ""]
  23.   --defaultNumberType   Default number type.                                         [choices: "number", "integer"] [default: "number"]
  24.   --tsNodeRegister      Use ts-node/register (needed for require typescript files).  [boolean] [default: false]
  25. ```

Programmatic use


  1. ```ts
  2. import { resolve } from "path";

  3. import * as TJS from "typescript-json-schema";

  4. // optionally pass argument to schema generator
  5. const settings: TJS.PartialArgs = {
  6.     required: true,
  7. };

  8. // optionally pass ts compiler options
  9. const compilerOptions: TJS.CompilerOptions = {
  10.     strictNullChecks: true,
  11. };

  12. // optionally pass a base path
  13. const basePath = "./my-dir";

  14. const program = TJS.getProgramFromFiles(
  15.   [resolve("my-file.ts")],
  16.   compilerOptions,
  17.   basePath
  18. );

  19. // We can either get the schema for one file and one type...
  20. const schema = TJS.generateSchema(program, "MyType", settings);

  21. // ... or a generator that lets us incrementally get more schemas

  22. const generator = TJS.buildGenerator(program, settings);

  23. // generator can be also reused to speed up generating the schema if usecase allows:
  24. const schemaWithReusedGenerator = TJS.generateSchema(program, "MyType", settings, [], generator);

  25. // all symbols
  26. const symbols = generator.getUserSymbols();

  27. // Get symbols for different types from generator.
  28. generator.getSchemaForSymbol("MyType");
  29. generator.getSchemaForSymbol("AnotherType");
  30. ```

  1. ```ts
  2. // In larger projects type names may not be unique,
  3. // while unique names may be enabled.
  4. const settings: TJS.PartialArgs = {
  5.     uniqueNames: true,
  6. };

  7. const generator = TJS.buildGenerator(program, settings);

  8. // A list of all types of a given name can then be retrieved.
  9. const symbolList = generator.getSymbols("MyType");

  10. // Choose the appropriate type, and continue with the symbol's unique name.
  11. generator.getSchemaForSymbol(symbolList[1].name);

  12. // Also it is possible to get a list of all symbols.
  13. const fullSymbolList = generator.getSymbols();
  14. ```

`getSymbols('')` and `getSymbols()` return an array of `SymbolRef`, which is of the following format:

  1. ```ts
  2. type SymbolRef = {
  3.     name: string;
  4.     typeName: string;
  5.     fullyQualifiedName: string;
  6.     symbol: ts.Symbol;
  7. };
  8. ```

getUserSymbols and getMainFileSymbols return an array of string.

Annotations


The schema generator converts annotations to JSON schema properties.

For example

  1. ```ts
  2. export interface Shape {
  3.     /**
  4.      * The size of the shape.
  5.      *
  6.      * @minimum 0
  7.      * @TJS-type integer
  8.      */
  9.     size: number;
  10. }
  11. ```

will be translated to

  1. ``` json
  2. {
  3.     "$ref": "#/definitions/Shape",
  4.     "$schema": "http://json-schema.org/draft-07/schema#",
  5.     "definitions": {
  6.         "Shape": {
  7.             "properties": {
  8.                 "size": {
  9.                     "description": "The size of the shape.",
  10.                     "minimum": 0,
  11.                     "type": "integer"
  12.                 }
  13.             },
  14.             "type": "object"
  15.         }
  16.     }
  17. }
  18. ```

Note that we needed to use @TJS-type instead of just @type because of an issue with the typescript compiler.

You can also override the type of array items, either listing each field in its own annotation or one
annotation with the full JSON of the spec (for special cases). This replaces the item types that would
have been inferred from the TypeScript type of the array elements.

Example:

  1. ```ts
  2. export interface ShapesData {
  3.     /**
  4.      * Specify individual fields in items.
  5.      *
  6.      * @items.type integer
  7.      * @items.minimum 0
  8.      */
  9.     sizes: number[];

  10.     /**
  11.      * Or specify a JSON spec:
  12.      *
  13.      * @items {"type":"string","format":"email"}
  14.      */
  15.     emails: string[];
  16. }
  17. ```

Translation:

  1. ``` json
  2. {
  3.     "$ref": "#/definitions/ShapesData",
  4.     "$schema": "http://json-schema.org/draft-07/schema#",
  5.     "definitions": {
  6.         "Shape": {
  7.             "properties": {
  8.                 "sizes": {
  9.                     "description": "Specify individual fields in items.",
  10.                     "items": {
  11.                         "minimum": 0,
  12.                         "type": "integer"
  13.                     },
  14.                     "type": "array"
  15.                 },
  16.                 "emails": {
  17.                     "description": "Or specify a JSON spec:",
  18.                     "items": {
  19.                         "format": "email",
  20.                         "type": "string"
  21.                     },
  22.                     "type": "array"
  23.                 }
  24.             },
  25.             "type": "object"
  26.         }
  27.     }
  28. }
  29. ```

This same syntax can be used for contains and additionalProperties.

integer type alias


If you create a type alias integer for number it will be mapped to the integer type in the generated JSON schema.

Example:

  1. ```typescript
  2. type integer = number;
  3. interface MyObject {
  4.     n: integer;
  5. }
  6. ```

Note: this feature doesn't work for generic types & array types, it mainly works in very simple cases.

require a variable from a file


(for requiring typescript files is needed to set argument tsNodeRegister to true)

When you want to import for example an object or an array into your property defined in annotation, you can use require.

Example:

  1. ```ts
  2. export interface InnerData {
  3.     age: number;
  4.     name: string;
  5.     free: boolean;
  6. }

  7. export interface UserData {
  8.     /**
  9.      * Specify required object
  10.      *
  11.      * @examples require("./example.ts").example
  12.      */
  13.     data: InnerData;
  14. }
  15. ```

file example.ts

  1. ```ts
  2. export const example: InnerData[] = [{
  3.   age: 30,
  4.   name: "Ben",
  5.   free: false
  6. }]
  7. ```

Translation:

  1. ``` json
  2. {
  3.     "$schema": "http://json-schema.org/draft-07/schema#",
  4.     "properties": {
  5.         "data": {
  6.             "description": "Specify required object",
  7.             "examples": [
  8.                 {
  9.                     "age": 30,
  10.                     "name": "Ben",
  11.                     "free": false
  12.                 }
  13.             ],
  14.             "type": "object",
  15.             "properties": {
  16.                 "age": { "type": "number" },
  17.                 "name": { "type": "string" },
  18.                 "free": { "type": "boolean" }
  19.             },
  20.             "required": ["age", "free", "name"]
  21.         }
  22.     },
  23.     "required": ["data"],
  24.     "type": "object"
  25. }
  26. ```

Also 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'.

Note: For examples a required variable must be an array.

Background


Inspired and builds upon 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.

Debugging


npm run debug -- test/programs/type-alias-single/main.ts --aliasRefs true MyString

And connect via the debugger protocol.