JSON Schema to TypeScript

15.0.4 · active · verified Sun Apr 19

json-schema-to-typescript is a utility that compiles JSON Schemas into TypeScript type declarations, enabling strong typing for data structures defined in JSON. Currently at version 15.0.4, it offers both a command-line interface (CLI) for file-based conversions and a programmatic API for integrating into build processes or applications. It is actively maintained with regular updates. Key differentiators include its robust handling of various JSON Schema features like `allOf`, `anyOf`, `oneOf`, `definitions`, and `$ref` for both local and external references. It aims to provide a reliable way to keep TypeScript types synchronized with JSON Schema definitions, reducing manual type creation and potential discrepancies between data contracts and application code. The library supports customizable options for output formatting, banner comments, and how `additionalProperties` are handled, which is crucial for controlling the strictness of generated types. It's particularly useful for projects consuming APIs or data where JSON Schema is the source of truth, facilitating a 'schema-first' development approach.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically compile a JSON Schema to TypeScript types, both from an in-memory object and from a file, using common configuration options. It creates a temporary `schema.json` and outputs `types.d.ts`.

import { compile, Options } from 'json-schema-to-typescript';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';

async function generateTypes() {
  const schemaPath = path.join(process.cwd(), 'schema.json');
  const outputPath = path.join(process.cwd(), 'types.d.ts');

  const mySchema = {
    "title": "UserProfile",
    "description": "A schema for user profile data",
    "type": "object",
    "properties": {
      "id": { "type": "string", "format": "uuid" },
      "username": { "type": "string", "minLength": 3, "maxLength": 20 },
      "email": { "type": "string", "format": "email" },
      "age": { "type": "integer", "minimum": 0, "maximum": 120 },
      "isActive": { "type": "boolean", "default": true }
    },
    "required": ["id", "username", "email"]
  };

  // Save schema to a file for compileFromFile example (optional, but good for demo)
  await fs.writeFile(schemaPath, JSON.stringify(mySchema, null, 2));

  const options: Partial<Options> = {
    bannerComment: "/* eslint-disable */\n/** Automatically generated from JSON Schema */",
    additionalProperties: false,
    unreachableDefinitions: true
  };

  try {
    // Example 1: Compile from an in-memory JS object
    const tsFromObject = await compile(mySchema, 'UserProfile', options);
    console.log('Generated from object:\n', tsFromObject);

    // Example 2: Compile from a file
    const tsFromFile = await compileFromFile(schemaPath, options);
    await fs.writeFile(outputPath, tsFromFile);
    console.log(`Types generated to ${outputPath}`);
  } catch (error) {
    console.error('Error generating types:', error);
  }
}

generateTypes();

view raw JSON →