JSON Schema to TypeScript Converter

0.14.3 · active · verified Sun Apr 19

This package facilitates the automatic conversion of JSON Schema definitions into TypeScript interfaces and types. It is currently at version 0.14.3 and appears to be actively maintained, with its last publish occurring four days ago as of the current date, indicating a relatively frequent release cadence. A key differentiator is its robust handling of standard JSON Schema features like `$ref` and `$defs` for modular schema definitions, and its ability to process arrays of defined types seamlessly into TypeScript arrays. Unlike some alternative tools that focus on generating JSON Schema *from* TypeScript code, this library specifically targets the generation of TypeScript *from* existing JSON Schema, providing a critical tool for schema-first development workflows. It operates with minimal dependencies and is part of the broader `constructive-io/dev-utils` monorepo, although it is designed for general-purpose use.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import the `generateTypeScript` function and convert a sample JSON Schema object for a 'User' into a TypeScript interface string, then write it to a file.

import { generateTypeScript } from 'schema-typescript';
import * as fs from 'node:fs/promises';

const userSchema = {
  "$id": "https://example.com/user.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "format": "uuid"
    },
    "name": {
      "type": "string",
      "description": "Full name of the user"
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "isActive": {
      "type": "boolean",
      "default": true
    }
  },
  "required": ["id", "name", "email"]
};

async function generateUserTypes() {
  try {
    const tsDefinition = await generateTypeScript(userSchema, 'User');
    await fs.writeFile('src/types/user.d.ts', tsDefinition);
    console.log('TypeScript types for User generated successfully to src/types/user.d.ts');
    console.log('\nGenerated TypeScript:\n', tsDefinition);
  } catch (error) {
    console.error('Failed to generate TypeScript types:', error);
  }
}

generateUserTypes();

view raw JSON →