TypeScript JSON Schema Generator
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
-
Error: ENOENT: no such file or directory, stat 'path/to/tsconfig.json'
cause The provided `tsconfig.json` path or input TypeScript file path is incorrect or the file does not exist.fixVerify the absolute path to your `tsconfig.json` or `.ts` files. Use `path.resolve()` for robustness. Ensure the files are accessible from where the script is run. -
Symbol 'MyType' not found in program.
cause The specified TypeScript type or interface name (`MyType`) does not exist in the provided TypeScript program or is not exported.fixDouble-check the type name for typos and ensure the type is correctly defined and exported in the TypeScript files included in the `getProgramFromFiles` call. -
TypeError: Cannot read properties of undefined (reading 'getSchemaForSymbol')
cause The `generator` object is `null` or `undefined`, typically because `TJS.buildGenerator` failed to initialize due to issues with the TypeScript program or settings.fixInspect the `program` object returned by `TJS.getProgramFromFiles` for errors. Ensure `filePaths` and `compilerOptions` are valid. Log the `generator` to see if it was successfully created.
Warnings
- deprecated The library is explicitly stated to be in 'maintenance mode', suggesting minimal new feature development and a slower pace for bug fixes. Users seeking a more actively developed or feature-rich solution are advised to consider alternatives.
- gotcha When using the programmatic API, ensure `TJS.getProgramFromFiles` is called with the correct file paths, compiler options, and a valid base path. Incorrect paths or configurations can lead to errors in type resolution or schema generation.
- gotcha Default behavior for `additionalProperties` is `true` unless explicitly set to `false` via `--noExtraProps` option (CLI) or `noExtraProps: true` in settings (programmatic API). This can lead to less strict schemas than intended.
- gotcha The library uses JSDoc annotations for certain schema features, but some require specific prefixes (e.g., `@TJS-type` instead of `@type`) due to TypeScript compiler limitations.
Install
-
npm install typescript-json-schema -
yarn add typescript-json-schema -
pnpm add typescript-json-schema
Imports
- buildGenerator
import { buildGenerator } from 'typescript-json-schema';import * as TJS from 'typescript-json-schema'; const generator = TJS.buildGenerator(program, settings);
- getProgramFromFiles
const { getProgramFromFiles } = require('typescript-json-schema');import * as TJS from 'typescript-json-schema'; const program = TJS.getProgramFromFiles(filePaths, compilerOptions, basePath);
- PartialArgs
import * as TJS from 'typescript-json-schema'; const settings: TJS.PartialArgs = { required: true };
Quickstart
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);