ts-json-schema-generator

Generate JSON schema from your Typescript sources

README

ts-json-schema-generator


Test codecov npm version


Inspired by [YousefED/typescript-json-schema](https://github.com/YousefED/typescript-json-schema). Here's the differences list:

-   this implementation avoids the use of typeChecker.getTypeAtLocation() (so probably it keeps correct type aliases)
-   processing AST and formatting JSON schema have been split into two independent steps
-   not exported types, interfaces, enums are not exposed in the definitions section in the JSON schema

Contributors


This project is made possible by a community of contributors. We welcome contributions of any kind (issues, code, documentation, examples, tests,...). Please read our code of conduct.

CLI Usage


  1. ``` sh
  2. npm install --save ts-json-schema-generator
  3. ./node_modules/.bin/ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'
  4. ```

Note that different platforms (e.g. Windows) may use different path separators so you may have to adjust the command above.

Programmatic Usage


  1. ``` js
  2. // main.js

  3. const tsj = require("ts-json-schema-generator");
  4. const fs = require("fs");

  5. /** @type {import('ts-json-schema-generator/dist/src/Config').Config} */
  6. const config = {
  7.     path: "path/to/source/file",
  8.     tsconfig: "path/to/tsconfig.json",
  9.     type: "*", // Or if you want to generate schema for that one type only
  10. };

  11. const output_path = "path/to/output/file";

  12. const schema = tsj.createGenerator(config).createSchema(config.type);
  13. const schemaString = JSON.stringify(schema, null, 2);
  14. fs.writeFile(output_path, schemaString, (err) => {
  15.     if (err) throw err;
  16. });
  17. ```

Run the schema generator via node main.js.

Custom formatting


Extending the built-in formatting is possible by creating a custom formatter and adding it to the main formatter:

1. First we create a formatter, in this case for formatting function types:

  1. ```ts
  2. // my-function-formatter.ts
  3. import { BaseType, Definition, FunctionType, SubTypeFormatter } from "ts-json-schema-generator";
  4. import ts from "typescript";

  5. export class MyFunctionTypeFormatter implements SubTypeFormatter {
  6.     // You can skip this line if you don't need childTypeFormatter
  7.     public constructor(private childTypeFormatter: TypeFormatter) {}

  8.     public supportsType(type: FunctionType): boolean {
  9.         return type instanceof FunctionType;
  10.     }

  11.     public getDefinition(type: FunctionType): Definition {
  12.         // Return a custom schema for the function property.
  13.         return {
  14.             type: "object",
  15.             properties: {
  16.                 isFunction: {
  17.                     type: "boolean",
  18.                     const: true,
  19.                 },
  20.             },
  21.         };
  22.     }

  23.     // If this type does NOT HAVE children, generally all you need is:
  24.     public getChildren(type: FunctionType): BaseType[] {
  25.         return [];
  26.     }

  27.     // However, if children ARE supported, you'll need something similar to
  28.     // this (see src/TypeFormatter/{Array,Definition,etc}.ts for some examples):
  29.     public getChildren(type: FunctionType): BaseType[] {
  30.         return this.childTypeFormatter.getChildren(type.getType());
  31.     }
  32. }
  33. ```

2. Then we add the formatter as a child to the core formatter using the augmentation callback:

  1. ```ts
  2. import { createProgram, createParser, SchemaGenerator, createFormatter } from "ts-json-schema-generator";
  3. import { MyFunctionTypeFormatter } from "./my-function-formatter.ts";
  4. import fs from "fs";

  5. const config = {
  6.     path: "path/to/source/file",
  7.     tsconfig: "path/to/tsconfig.json",
  8.     type: "*", // Or if you want to generate schema for that one type only
  9. };

  10. // We configure the formatter an add our custom formatter to it.
  11. const formatter = createFormatter(config, (fmt, circularReferenceTypeFormatter) => {
  12.     // If your formatter DOES NOT support children, e.g. getChildren() { return [] }:
  13.     fmt.addTypeFormatter(new MyFunctionTypeFormatter());
  14.     // If your formatter DOES support children, you'll need this reference too:
  15.     fmt.addTypeFormatter(new MyFunctionTypeFormatter(circularReferenceTypeFormatter));
  16. });

  17. const program = createProgram(config);
  18. const parser = createParser(program, config);
  19. const generator = new SchemaGenerator(program, parser, formatter, config);
  20. const schema = generator.createSchema(config.type);

  21. const schemaString = JSON.stringify(schema, null, 2);
  22. fs.writeFile(output_path, schemaString, (err) => {
  23.     if (err) throw err;
  24. });
  25. ```

Custom parsing


Similar to custom formatting, extending the built-in parsing works practically the same way:

1. First we create a parser, in this case for parsing construct types:

  1. ```ts
  2. // my-constructor-parser.ts
  3. import { Context, StringType, ReferenceType, BaseType, SubNodeParser } from "ts-json-schema-generator";
  4. // use typescript exported by TJS to avoid version conflict
  5. import ts from "ts-json-schema-generator";

  6. export class MyConstructorParser implements SubNodeParser {
  7.     supportsNode(node: ts.Node): boolean {
  8.         return node.kind === ts.SyntaxKind.ConstructorType;
  9.     }
  10.     createType(node: ts.Node, context: Context, reference?: ReferenceType): BaseType | undefined {
  11.         return new StringType(); // Treat constructors as strings in this example
  12.     }
  13. }
  14. ```

2. Then we add the parser as a child to the core parser using the augmentation callback:

  1. ```ts
  2. import { createProgram, createParser, SchemaGenerator, createFormatter } from "ts-json-schema-generator";
  3. import { MyConstructorParser } from "./my-constructor-parser.ts";
  4. import fs from "fs";

  5. const config = {
  6.     path: "path/to/source/file",
  7.     tsconfig: "path/to/tsconfig.json",
  8.     type: "*", // Or if you want to generate schema for that one type only
  9. };

  10. const program = createProgram(config);

  11. // We configure the parser an add our custom parser to it.
  12. const parser = createParser(program, config, (prs) => {
  13.     prs.addNodeParser(new MyConstructorParser());
  14. });

  15. const formatter = createFormatter(config);
  16. const generator = new SchemaGenerator(program, parser, formatter, config);
  17. const schema = generator.createSchema(config.type);

  18. const schemaString = JSON.stringify(schema, null, 2);
  19. fs.writeFile(output_path, schemaString, (err) => {
  20.     if (err) throw err;
  21. });
  22. ```

Options


  1. ```
  2. -p, --path 'index.ts'
  3.     The path to the TypeScript source file. If this is not provided, the type will be searched in the project specified in the `.tsconfig`.

  4. -t, --type 'My.Type.Name'
  5.     The type the generated schema will represent. If omitted, the generated schema will contain all
  6.     types found in the files matching path. The same is true if '*' is specified.

  7. -i, --id 'generatedSchemaId'
  8.     The `$id` of the generated schema. If omitted, there will be no `$id`.

  9. -e, --expose <all|none|export>
  10.     all: Create shared $ref definitions for all types.
  11.     none: Do not create shared $ref definitions.
  12.     export (default): Create shared $ref definitions only for exported types (not tagged as `@internal`).

  13. -f, --tsconfig 'my/project/tsconfig.json'
  14.     Use a custom tsconfig file for processing typescript (see https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) instead of the default:
  15.     {
  16.         "compilerOptions": {
  17.             "noEmit": true,
  18.             "emitDecoratorMetadata": true,
  19.             "experimentalDecorators": true,
  20.             "target": "ES5",
  21.             "module": "CommonJS",
  22.             "strictNullChecks": false,
  23.         }
  24.     }

  25. -j, --jsDoc <extended|none|basic>
  26.     none: Do not use JsDoc annotations.
  27.     basic: Read JsDoc annotations to provide schema properties.
  28.     extended (default): Also read @nullable, and @asType annotations.

  29. --unstable
  30.     Do not sort properties.

  31. --strict-tuples
  32.     Do not allow additional items on tuples.

  33. --no-top-ref
  34.     Do not create a top-level $ref definition.

  35. --no-type-check
  36.     Skip type checks for better performance.

  37. --no-ref-encode
  38.     Do not encode references. According to the standard, references must be valid URIs but some tools do not support encoded references.

  39. --validation-keywords
  40.     Provide additional validation keywords to include.

  41. -o, --out
  42.     Specify the output file path. Without this option, the generator logs the response in the console.

  43. --additional-properties <true|false>
  44.     Controls whether or not to allow additional properties for objects that have no index signature.

  45.     true: Additional properties are allowed
  46.     false (default): Additional properties are not allowed

  47. --minify
  48.     Minify generated schema (default: false)
  49. ```

Current state


-   interface types
-   enum types
-   union, tuple, type[] types
-   Date, RegExp, URL types
-   string, boolean, number types
-   "value", 123, true, false, null, undefined literals
-   type aliases
-   generics
-   typeof
-   keyof
-   conditional types

Run locally


yarn --silent run run --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'

Debug


yarn --silent run debug --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'

And connect via the debugger protocol.

AST Explorer is amazing for developers of this tool!

Publish


Publishing is handled by a 2-branch pre-release process, configured inpublish-auto.yml. All changes should be based off the default next branch, and are published automatically.

-   PRs made into the default branch are auto-deployed to the next pre-release tag on NPM. The result can be installed with npm install ts-json-schema-generator@next
    -   When merging into next, please use the squash and merge strategy.
-   To release a new stable version, open a PR from next into stable using this compare link.
    -   When merging from next into stable, please use the create a merge commit strategy.