Other languages: 中文
A Typescript transformer plugin to convert Typescript type to JSON Schema.
Inspired by vega/ts-json-schema-generator
and ipetrovic11/ts-transformer-json-schema
$ pnpm add types2schema
// tsconfig.json
{
"compilerOptions": {
// ...
"plugins": [{ "transform": "types2schema/lib/transformer" }]
}
// ...
}
Unfortunately, TypeScript itself does not currently provide any easy way to use custom transformers, so you have to use ts-patch
or other lib which support transformer to make this plugin available.
Why not use ttypescript
? ttypescript
didn't support alter diagnostics, but we can't avoid writing a error type whose inner has unsupported type, so we chose a lib support we add diagnostics to print transformer errors.
import { schema } from 'types2schema';
const validateSchema = schema<string>();
Compile Result:
import { schema } from 'types2schema';
const validateSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'string',
};
- Primitive Types (null、number、string、boolean)
- Literal
- Interface
- Type Literal
- Mapped Type
- Enum
- Union Type
- Intersection Type
- Array
- Tuple
All the above types support generic.
If you want more support more about the support situation, please check Unit Tests.
Sometime you want to add some JSON Schema specific fields like:
{
"type": "string",
"minLength": 2,
"maxLength": 10
}
In these case, you can use jsdoc tags to describe these extra schema fields and their value:
interface IApi {
/**
* @minLength 2
* @maxLength 10
*/
name: string;
}
Transformer will parse tags on object properties, interface and object type alias. But because object type would be transformed to definition reference, so property jsdoc tags will be invalidation when it's value type is a other object type.
Example:
/**
* ✅ available
* @additionalProperties true
*/
interface IPerson {
name: string;
}
interface IApi {
/**
* ❌ unavailable
* @additionalProperties false
*/
person: IPerson;
}
The tag value would be considered as a json string. When failed, treat it as a normal string.
Usually, undefined
is not a type that can be converted to Schema, but when it is used as a property value of an object, Typescript will mark this property as an optional property. The plugin has some special process to be compatible with this type of writing (But we still recommend use the optional mark ?
when writing object), but using undefined
in other scenes will trigger a transformer error.
✅:
interface IApi {
name: string | undefined;
}
// Equal to
interface IApi {
name?: string;
}
❌:
schema<undefined>();
type Union = string | undefined;
schema<Union>();
type Tuple = [string | undefined, undefined];
schema<Tuple>();