JSON Schema to TypeScript (Forked)

10.2.0 · deprecated · verified Sun Apr 19

The `rm-json-schema-to-typescript` package is a fork of the popular `json-schema-to-typescript` library, designed to compile JSON schemas into TypeScript interfaces and typings. Currently at version 10.2.0, this package offers modified reference resolving behavior compared to its upstream counterpart. Its development status is tied to the original project, with an explicit intention to be deprecated once the core changes implemented in this fork are accepted into the main `json-schema-to-typescript` repository. As a fork, its release cadence is likely reactive to critical fixes or its specific feature set rather than a strict schedule. It aims to provide a drop-in replacement where its altered reference resolution is beneficial, but users should be aware of its temporary nature and plan for eventual migration.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to compile a JSON schema object into a TypeScript interface using the `compile` function, and how it writes the output to a file.

import { compile, compileFromFile } from 'json-schema-to-typescript';
import * as fs from 'fs/promises';

// Define a simple JSON schema programmatically
const mySchema = {
  title: 'UserSchema',
  type: 'object',
  properties: {
    id: { type: 'string', format: 'uuid' },
    name: { type: 'string' },
    email: { type: 'string', format: 'email' },
    isActive: { type: 'boolean', default: true }
  },
  required: ['id', 'name', 'email'],
  additionalProperties: false
};

async function generateTypes() {
  try {
    // Compile from a JS object in memory
    const tsFromObject = await compile(mySchema, 'UserSchema');
    console.log('Generated from object:\n', tsFromObject);
    // For demonstration, write to a dummy file. In real use, this might be dynamic.
    await fs.writeFile('user.d.ts', tsFromObject);

    // Example of compiling from a file (assuming 'example.json' exists)
    // For a real scenario, you'd create this file first.
    // const tsFromFile = await compileFromFile('example.json');
    // await fs.writeFile('example.d.ts', tsFromFile);

    console.log('TypeScript types generated successfully.');
  } catch (error) {
    console.error('Error generating types:', error);
  }
}

generateTypes();

view raw JSON →