TypeScript JSON Schema Generator

2.9.0 · active · verified Sun Apr 19

ts-json-schema-generator is a robust tool that generates JSON Schema (supporting Draft 07, 2019-09, and 2020-12) directly from TypeScript types, interfaces, and classes. Unlike some alternatives, it processes the TypeScript Abstract Syntax Tree (AST) using the TypeScript compiler API, which allows for accurate handling of advanced TypeScript features such as generics, mapped types, union types, conditional types, and type aliases. The package, currently at version 2.9.0, is actively maintained with frequent minor updates and bug fixes. It serves as an extended version of `typescript-to-json-schema`, specifically designed to provide better support for type alias resolution and a more consistent schema output. It offers both a command-line interface (CLI) for quick generation and a programmatic API for integration into build pipelines, making it a versatile choice for ensuring data contracts align between TypeScript code and JSON-based systems.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates programmatic generation of a JSON schema for a specific TypeScript interface using a local `tsconfig.json`.

import { createGenerator } from 'ts-json-schema-generator';
import * as fs from 'fs';
import * as path from 'path';

// 1. Define your TypeScript types in a file, e.g., 'src/types.ts'
// export interface User {
//   id: string;
//   name: string;
//   email?: string;
//   isActive: boolean;
//   roles: Array<'admin' | 'editor' | 'viewer'>;
//   createdAt: Date;
// }

// 2. Configure the generator
const config = {
  path: path.resolve(__dirname, 'src/types.ts'),
  tsconfig: path.resolve(__dirname, 'tsconfig.json'),
  type: 'User', // Specify the type name to generate schema for
  skipTypeCheck: false, // Set to true for faster generation, but less strict validation
  additionalProperties: true, // Allow undeclared properties by default (matches JSON Schema spec more loosely)
};

// 3. Ensure a tsconfig.json exists for the project
// {
//   "compilerOptions": {
//     "target": "ES2022",
//     "module": "NodeNext",
//     "strict": true,
//     "esModuleInterop": true,
//     "skipLibCheck": true,
//     "forceConsistentCasingInFileNames": true
//   },
//   "include": ["src/**/*.ts"]
// }

// 4. Generate the schema
try {
  const schemaGenerator = createGenerator(config);
  const schema = schemaGenerator.createSchema(config.type);

  const outputPath = path.resolve(__dirname, 'generated/user.schema.json');
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
  fs.writeFileSync(outputPath, JSON.stringify(schema, null, 2));

  console.log(`JSON Schema for type '${config.type}' generated successfully at ${outputPath}`);
} catch (error) {
  console.error('Failed to generate JSON schema:', error);
  process.exit(1);
}

view raw JSON →