Registry / serialization / ts-json-schema-generator

ts-json-schema-generator

JSON →
library2.9.0jsnpmunverified

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.

npm install ts-json-schema-generator
INSTALL
IMPORT
SIG · TS-JSON-SCHEMA-GEN
T
ts-json-schema-generator
serializationjavascriptv2.9.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createGenerator
import { createGenerator } from 'ts-json-schema-generator';
const createGenerator = require('ts-json-schema-generator').createGenerator;
This is the primary function for programmatic schema generation. The CommonJS `require` pattern is generally discouraged in modern TypeScript projects.
Config
import type { Config } from 'ts-json-schema-generator';
import { Config } from 'ts-json-schema-generator'; // Importing a type as a value
The `Config` interface defines the configuration options for `createGenerator`. It should be imported as a type for type safety without bundling overhead. Older CommonJS examples might import it from a deep path like `dist/src/Config`.
Schema
import type { Schema } from 'ts-json-schema-generator';
Represents the generated JSON Schema object. Primarily used for type annotation, so `import type` is appropriate.

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); }
ts-json-schema-generator --version
Debug
Known issues
gotchaOnly 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.
fix
Ensure all TypeScript types and interfaces you intend to generate schemas for are exported from their respective files.
affects: >=1.0.0
gotchaWhen 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.
fix
Always quote paths containing wildcards in your CLI commands, e.g., `npx ts-json-schema-generator --path 'src/**/*.ts' --type 'MyType'`.
affects: >=1.0.0
gotchaComplex 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.
fix
Try simplifying the TypeScript types where possible. For external library types, consider creating a simpler alias or a subset interface that only includes the properties relevant for your schema generation. Report specific issues on GitHub.
affects: >=1.0.0
gotchaThe 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.
fix
Explicitly control `additionalProperties` via the configuration option (`additionalProperties: true` or `false`) or use JSDoc annotations (`@additionalProperties true` / `@additionalProperties false`) on your TypeScript types.
affects: >=1.0.0
gotchaIncorrect 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.
fix
Verify that the `path` and `tsconfig` options in your configuration (or CLI arguments) correctly point to your source files and project's `tsconfig.json`. Adjust `compilerOptions.lib` in `tsconfig.json` if encountering 'Duplicate identifier' errors, especially with built-in types like `DOM` or `ESNext`.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Type 'MyType' not found in file 'path/to/my-file.ts'.
The specified type name is incorrect, not exported, or the file path/tsconfig.json configuration is preventing the generator from finding it.
fix
Double-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').
The generator encountered an unsupported or unusually complex TypeScript AST node, often from external libraries or highly specialized syntax.
fix
Simplify 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'.
This usually indicates a conflict in type definitions, often due to multiple `lib` configurations in `tsconfig.json` or conflicting `@types` packages.
fix
Review 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
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.
fix
Ensure 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' ...`.
Upgrade
Version history
2.9.0latest on npm
Audit
Dependencies
typescriptrequiredRequired for parsing TypeScript source files and generating schemas; it leverages the TypeScript compiler API internally.
Agent activity
17 hits · last 30 days
node
16
OpenAI (training)
1
Resources