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-generatorVerified import paths — ran on the pinned version, not inferred.
Demonstrates programmatic generation of a JSON schema for a specific TypeScript interface using a local `tsconfig.json`.
Ensure all TypeScript types and interfaces you intend to generate schemas for are exported from their respective files.
Always quote paths containing wildcards in your CLI commands, e.g., `npx ts-json-schema-generator --path 'src/**/*.ts' --type 'MyType'`.
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.
Explicitly control `additionalProperties` via the configuration option (`additionalProperties: true` or `false`) or use JSDoc annotations (`@additionalProperties true` / `@additionalProperties false`) on your TypeScript types.
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`.
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.
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.
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.
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' ...`.