JSON Schema to TypeScript (Lite)

15.0.0 · active · verified Sun Apr 19

json-schema-to-typescript-lite is a focused fork of json-schema-to-typescript, designed to compile JSON schemas into TypeScript typings with a significantly reduced dependency footprint. The current stable version is 15.0.0. This package emphasizes programmatic usage, foregoing CLI support and internal Prettier integrations for a leaner build. It achieves smaller bundle sizes by replacing heavy dependencies like `lodash` with `lodash-es` (bundled) and targets modern ESNext environments. It offers dual module support (ESM and CJS) and includes support for custom naming options, making it suitable for environments where bundle size and minimal dependencies are critical considerations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `compile` to convert a JSON schema object into a TypeScript interface string, including common options.

import { compile } from 'json-schema-to-typescript-lite';

async function generateUserTypes() {
  const userSchema = {
    type: 'object',
    properties: {
      id: { type: 'string', description: 'Unique user identifier' },
      name: { type: 'string', minLength: 1 },
      email: { type: 'string', format: 'email' },
      age: { type: 'number', minimum: 0, maximum: 120 },
      isActive: { type: 'boolean', default: true },
      roles: {
        type: 'array',
        items: { type: 'string', enum: ['admin', 'editor', 'viewer'] },
        minItems: 1
      }
    },
    required: ['id', 'name', 'email', 'isActive'],
    additionalProperties: false,
    title: 'UserSchema', // Used as base name if not overridden by second arg
    description: 'Defines the structure for a user object.'
  };

  try {
    const tsDefinition = await compile(userSchema, 'IUser', {
      bannerComment: '/* Generated by json-schema-to-typescript-lite */',
      declareExternallyReferenced: false,
      unknownAny: false, // Prefer 'unknown' over 'any'
      customName: (id: string) => id === 'IUser' ? 'MyCustomUserType' : id,
    });
    console.log(tsDefinition);
  } catch (error) {
    console.error('Failed to compile schema:', error);
  }
}

generateUserTypes().catch(console.error);

view raw JSON →