0.3.0 • Published 5 years ago

json-schema-to-type v0.3.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

npm version

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 type
    • single schema for all items
      • full support for array schemas as item schemas (currently resolves to )
      • full support for object schemas as item schemas (currently resolves to object[])
    • multiple items schemas (tuples)
    • additionalItems property
    • contains property
  • object type
    • required properties
    • patternProperties property
    • additionalProperties 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)
  • enum property
  • const property
  • definitions property (investigate $ref support)
  • if, then, else properties
  • allOf, anyOf, oneOf, not properties
0.3.0

5 years ago

0.2.0

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago