TypeScript JSON Schema Generator

0.67.1 · maintenance · verified Sun Apr 19

typescript-json-schema is a library designed to generate JSON Schema definitions directly from TypeScript source files. It operates by compiling the TypeScript program to extract comprehensive type information and then translating this into JSON Schema, including features like required properties, inheritance (`extends`), JSDoc annotation keywords, and default values from property initializers. The current stable version is 0.67.1. The project is explicitly stated to be in "maintenance mode", indicating a slower release cadence and less active feature development compared to its past. While lightweight, the maintainers suggest `ts-json-schema-generator` for a more feature-rich and actively developed alternative, highlighting `typescript-json-schema`'s primary differentiator as its use of the TypeScript compiler internally, enabling advanced scenarios.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates programmatic JSON Schema generation from a TypeScript interface using temporary files for demonstration. It configures the generator with common settings like `required` properties and `strictNullChecks` to produce a comprehensive schema, then prints it to the console.

import * as TJS from 'typescript-json-schema';
import { resolve } from 'path';
import * as fs from 'fs';

// Define your TypeScript interface or type
const typeScriptCode = `
  export interface User {
    id: number;
    name: string;
    email?: string;
    isActive: boolean;
    roles: ('admin' | 'user')[];
    createdAt: Date;
  }
`;

const tempFilePath = resolve(__dirname, 'temp.ts');
fs.writeFileSync(tempFilePath, typeScriptCode);

// Optionally pass argument to schema generator
const settings: TJS.PartialArgs = {
  required: true, // Generate 'required' array for non-optional properties
  noExtraProps: true, // Disable additional properties in objects by default
  strictNullChecks: true, // Make values non-nullable by default
  titles: true, // Create titles in the output schema
};

// Optionally pass ts compiler options
const compilerOptions: TJS.CompilerOptions = {
  strictNullChecks: true,
  esModuleInterop: true,
};

// Get a TypeScript Program from the file
const program = TJS.getProgramFromFiles(
  [tempFilePath],
  compilerOptions,
  __dirname // Base path for the program
);

// Build the schema generator
const generator = TJS.buildGenerator(program, settings);

// Generate the schema for a specific type (e.g., 'User')
const schema = generator?.getSchemaForSymbol('User');

if (schema) {
  console.log(JSON.stringify(schema, null, 2));
} else {
  console.error('Failed to generate schema for User.');
}

// Clean up the temporary file
fs.unlinkSync(tempFilePath);

view raw JSON →