0.3.0 • Published 5 years ago
json-schema-to-type v0.3.0
json-schema-to-type
A compile-time TypeScript library that can generate the type of a JSON instance from a JSON Schema object type.
Requires TypeScript >=3.4
Installation
npm install -D json-schema-to-type
yarn -D add json-schema-to-type
Usage
import { JsonSchemaToType } from 'json-schema-to-type';
const schema = {
type: 'object',
properties: {
firstName: {
type: 'string',
},
lastName: {
type: 'string',
},
age: {
type: 'integer',
},
address: {
type: 'object',
properties: {
addressLine1: {
type: 'string',
},
addressLine2: {
type: 'string',
},
postCode: {
type: 'string',
},
},
required: ['addressLine1', 'postCode'],
},
phoneNumbers: {
type: 'array',
items: {
type: ['string', 'object'],
properties: {
areaCode: { type: 'number' },
localNumber: { type: 'number' },
},
required: ['localNumber'],
},
},
},
required: ['firstName', 'lastName', 'phoneNumbers'],
} as const;
type Type = JsonSchemaToType<typeof schema>;
The resulting type of Type
will be equivalent to:
type Type = {
firstName: string;
lastName: string;
age?: number;
address?: {
addressLine1: string;
addressLine2?: string;
postCode: string;
};
phoneNumbers: (string | { areaCode?: number; localNumber: number })[];
};
Development status
The support for many JSON Schema features is still missing. Things to implement:
array
typeobject
type- required properties
patternProperties
propertyadditionalProperties
property
- multi-type schemas
- full support for
array
schemas in multi-type schemas (currently resolves to []) - full support for
object
schemas in multi-type schemas (currently resolves to object)
- full support for
enum
propertyconst
propertydefinitions
property (investigate$ref
support)if
,then
,else
propertiesallOf
,anyOf
,oneOf
,not
properties