typescript-json-schema
![npm version](https://img.shields.io/npm/v/@lemon-clown/typescript-json-schema.svg)
Generate json-schemas from your Typescript sources.
I sincerely suggest you use the original repository, as this repository/package is forked for demanding of myself (study and customization).
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 test examples.
Usage
Programmatic use
import { resolve } from 'path'
import * as TJS from '@lemon-clown/typescript-json-schema'
const settings: TJS.PartialArgs = {
ref: false,
required: true,
}
const compilerOptions: TJS.CompilerOptions = {
strictNullChecks: true
}
const basePath = './my-dir'
const program = TJS.getProgramFromFiles([resolve('my-file.ts')], compilerOptions, basePath)
const schema = TJS.generateSchema(program, 'MyType', settings)
const generator = TJS.buildGenerator(program, settings)
const symbols = generator.getUserSymbols()
generator.getSchemaForSymbol('MyType')
generator.getSchemaForSymbol('AnotherType')
const settings: TJS.PartialArgs = {
uniqueNames: true
}
const generator = TJS.buildGenerator(program, settings)
const symbolList = generator.getSymbols('MyType')
generator.getSchemaForSymbol(symbolList[1].name)
const fullSymbolList = generator.getSymbols()
getSymbols('<SymbolName>')
and getSymbols()
return an array of SymbolRef
, which is of the following format:
type SymbolRef = {
name: string
typeName: string
fullyQualifiedName: string
symbol: ts.Symbol
}
getUserSymbols
and getMainFileSymbols
return an array of string
.
Annotations
The schema generator converts annotations to JSON schema properties.
For example
export interface Shape {
size: number
}
will be translated to
{
"$ref": "#/definitions/Shape",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"Shape": {
"properties": {
"size": {
"description": "The size of the shape.",
"minimum": 0,
"type": "integer"
}
},
"type": "object"
}
}
}
Note that we needed to use @TJS-type
instead of just @type
because of an issue with the typescript compiler.
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.