{"id":12179,"library":"ts-json-schema-generator","title":"TypeScript JSON Schema Generator","description":"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.","status":"active","version":"2.9.0","language":"javascript","source_language":"en","source_url":"https://github.com/vega/ts-json-schema-generator","tags":["javascript","ts","typescript","json","schema","jsonschema"],"install":[{"cmd":"npm install ts-json-schema-generator","lang":"bash","label":"npm"},{"cmd":"yarn add ts-json-schema-generator","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-json-schema-generator","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for parsing TypeScript source files and generating schemas; it leverages the TypeScript compiler API internally.","package":"typescript","optional":false}],"imports":[{"note":"This is the primary function for programmatic schema generation. The CommonJS `require` pattern is generally discouraged in modern TypeScript projects.","wrong":"const createGenerator = require('ts-json-schema-generator').createGenerator;","symbol":"createGenerator","correct":"import { createGenerator } from 'ts-json-schema-generator';"},{"note":"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`.","wrong":"import { Config } from 'ts-json-schema-generator'; // Importing a type as a value","symbol":"Config","correct":"import type { Config } from 'ts-json-schema-generator';"},{"note":"Represents the generated JSON Schema object. Primarily used for type annotation, so `import type` is appropriate.","symbol":"Schema","correct":"import type { Schema } from 'ts-json-schema-generator';"}],"quickstart":{"code":"import { createGenerator } from 'ts-json-schema-generator';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n// 1. Define your TypeScript types in a file, e.g., 'src/types.ts'\n// export interface User {\n//   id: string;\n//   name: string;\n//   email?: string;\n//   isActive: boolean;\n//   roles: Array<'admin' | 'editor' | 'viewer'>;\n//   createdAt: Date;\n// }\n\n// 2. Configure the generator\nconst config = {\n  path: path.resolve(__dirname, 'src/types.ts'),\n  tsconfig: path.resolve(__dirname, 'tsconfig.json'),\n  type: 'User', // Specify the type name to generate schema for\n  skipTypeCheck: false, // Set to true for faster generation, but less strict validation\n  additionalProperties: true, // Allow undeclared properties by default (matches JSON Schema spec more loosely)\n};\n\n// 3. Ensure a tsconfig.json exists for the project\n// {\n//   \"compilerOptions\": {\n//     \"target\": \"ES2022\",\n//     \"module\": \"NodeNext\",\n//     \"strict\": true,\n//     \"esModuleInterop\": true,\n//     \"skipLibCheck\": true,\n//     \"forceConsistentCasingInFileNames\": true\n//   },\n//   \"include\": [\"src/**/*.ts\"]\n// }\n\n// 4. Generate the schema\ntry {\n  const schemaGenerator = createGenerator(config);\n  const schema = schemaGenerator.createSchema(config.type);\n\n  const outputPath = path.resolve(__dirname, 'generated/user.schema.json');\n  fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n  fs.writeFileSync(outputPath, JSON.stringify(schema, null, 2));\n\n  console.log(`JSON Schema for type '${config.type}' generated successfully at ${outputPath}`);\n} catch (error) {\n  console.error('Failed to generate JSON schema:', error);\n  process.exit(1);\n}\n","lang":"typescript","description":"Demonstrates programmatic generation of a JSON schema for a specific TypeScript interface using a local `tsconfig.json`."},"warnings":[{"fix":"Ensure all TypeScript types and interfaces you intend to generate schemas for are exported from their respective files.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always quote paths containing wildcards in your CLI commands, e.g., `npx ts-json-schema-generator --path 'src/**/*.ts' --type 'MyType'`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Explicitly control `additionalProperties` via the configuration option (`additionalProperties: true` or `false`) or use JSDoc annotations (`@additionalProperties true` / `@additionalProperties false`) on your TypeScript types.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"The specified type name is incorrect, not exported, or the file path/tsconfig.json configuration is preventing the generator from finding it.","error":"Error: Type 'MyType' not found in file 'path/to/my-file.ts'."},{"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.","cause":"The generator encountered an unsupported or unusually complex TypeScript AST node, often from external libraries or highly specialized syntax.","error":"Error: Unknown node 'SyntaxKind.JsxElement' (or similar 'SyntaxKind.OtherExpression', 'SyntaxKind.BinaryExpression')."},{"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.","cause":"This usually indicates a conflict in type definitions, often due to multiple `lib` configurations in `tsconfig.json` or conflicting `@types` packages.","error":"TS2300: Duplicate identifier 'Headers'."},{"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' ...`.","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.","error":"Error: Parameter 'files' must be an array of strings"}],"ecosystem":"npm"}