TypeScript JSON Schema Generator
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
-
Error: Type 'MyType' not found in file 'path/to/my-file.ts'.
cause The specified type name is incorrect, not exported, or the file path/tsconfig.json configuration is preventing the generator from finding it.fixDouble-check the type name for typos, ensure the type is `export`ed, and verify that the `path` and `tsconfig` settings correctly point to the file and project configuration. -
Error: Unknown node 'SyntaxKind.JsxElement' (or similar 'SyntaxKind.OtherExpression', 'SyntaxKind.BinaryExpression').
cause The generator encountered an unsupported or unusually complex TypeScript AST node, often from external libraries or highly specialized syntax.fixSimplify the TypeScript types involved, especially if they are heavily reliant on external JSX elements, complex expressions, or library-specific patterns. Consider creating simpler interfaces that derive from or represent the core data structure. -
TS2300: Duplicate identifier 'Headers'.
cause This usually indicates a conflict in type definitions, often due to multiple `lib` configurations in `tsconfig.json` or conflicting `@types` packages.fixReview your `tsconfig.json`'s `compilerOptions.lib` setting to ensure it doesn't include redundant or conflicting DOM/ES environments. Check for duplicate `@types` dependencies. -
Error: Parameter 'files' must be an array of strings
cause When using the CLI with a wildcard in the `--path` argument, the shell expanded the wildcard, leading the generator to receive multiple arguments instead of a single quoted string.fixEnsure that any paths containing wildcards (`*`) passed to the CLI via `--path` are enclosed in single or double quotes, e.g., `npx ts-json-schema-generator --path 'src/**/*.ts' ...`.
Warnings
- gotcha Only exported types, interfaces, and enums are exposed in the definitions section of the generated JSON schema. Types not explicitly exported will not be included or referenced.
- gotcha When using the CLI with path wildcards (e.g., `--path 'src/**/*.ts'`), it's crucial to quote the path. Without quotes, the shell might expand the wildcard, passing only the first matching file to the generator instead of the pattern, leading to incomplete schema generation.
- gotcha Complex TypeScript constructs, especially intricate generics, mapped types, or types from large third-party libraries (e.g., React, Node.js `lib.d.ts`), can sometimes lead to 'Unknown node' errors or incomplete/incorrect schema output.
- gotcha The behavior of `additionalProperties` for objects without index signatures can be unexpected. By default, it's often `false`, meaning properties not explicitly defined in the schema are disallowed. This might not align with intended 'open' objects.
- gotcha Incorrect or missing `tsconfig.json` configuration can lead to TypeScript compiler errors during schema generation, such as 'Cannot find module' or 'Duplicate identifier'. Ensure the `tsconfig.json` correctly includes all source files and specifies appropriate `lib` options.
Install
-
npm install ts-json-schema-generator -
yarn add ts-json-schema-generator -
pnpm add ts-json-schema-generator
Imports
- createGenerator
const createGenerator = require('ts-json-schema-generator').createGenerator;import { createGenerator } from 'ts-json-schema-generator'; - Config
import { Config } from 'ts-json-schema-generator'; // Importing a type as a valueimport type { Config } from 'ts-json-schema-generator'; - Schema
import type { Schema } from 'ts-json-schema-generator';
Quickstart
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);
}