CLI tool
vega/ts-json-schema-generator avatar
vega/ts-json-schema-generator

ts-json-schema-generator: Schema Generation for TypeScript Projects

Generate JSON schema from your Typescript sources

1,717 stars240 forksTypeScriptMIT

At a glance

What is it?
ts-json-schema-generator turns TypeScript source types into JSON Schema through a configurable CLI or the programmatic API. It is aimed at projects that need schemas derived from their existing type definitions, with particular attention to type aliases, references, JSDoc metadata and export visibility.
Who is it for?
Adopt ts-json-schema-generator when schema output must remain tied to exported TypeScript types and can be generated through Node.js or a build script. Do not choose it when an unresolved schema artifact is sufficient or when unexported declarations must appear in the root definitions.
Can I use it commercially?
Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository last received commits 6 days ago.
What is it written in?
Mainly TypeScript, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on October 20, 2026, and from our analysis. They are not legal advice.

Editorial analysis

Why ts-json-schema-generator Exists

ts-json-schema-generator addresses the gap between TypeScript declarations and a separate JSON Schema description. Teams often have interfaces and type aliases that already define application data, yet still need a schema for validation, documentation, API contracts or code generation. Maintaining both descriptions creates a synchronization problem. Generating the schema from TypeScript sources makes the type declaration the central input rather than a second manually maintained model.

The project is for developers who need a selected root type or a broader set of types from one or more TypeScript files. That includes library authors publishing data contracts and application teams embedding schema generation in a build workflow. It can also be called directly from a Node.js program when generation needs to be coordinated with other file operations.

The README identifies the project as an extended version of xiag-ag/typescript-to-json-schema and says it was inspired by YousefED/typescript-json-schema. Its stated differences are architectural and semantic. It avoids typeChecker.getTypeAtLocation(), which the documentation associates with preserving correct type aliases, and it separates AST processing from JSON Schema formatting. It also keeps unexported types, interfaces and enums out of definitions by default. Those choices matter more to an engineer than the broad similarity among schema generators because they affect which declarations become visible and how the conversion pipeline is composed.

TypeScript AST to Formatted JSON Schema

The documented design separates processing TypeScript syntax from formatting the resulting schema. That split makes the conversion more than a single formatter with parsing concerns embedded in it. The README also documents extension points for custom subtype formatters, including the ability to support a specific TypeScript-derived type and define the children it contains.

The CLI receives source paths through --path and selects output through --type. A value such as My.Type.Name requests one named type, while the programmatic example documents "*" as the type value for generating a schema beyond one named type. Source discovery relies on a glob supplied by the user. The shell must not expand that pattern before the program receives it, which is why the documentation quotes paths containing *.

TypeScript compiler settings come from tsconfig.json. By default, the command searches the current working directory and then parent directories until it finds one, continuing to the filesystem root if necessary. --tsconfig replaces that discovery process. This matters when schema generation needs compiler options that differ from those used for ordinary application compilation. The generated schema is controlled further by export exposure, JSDoc reading, tuple strictness, reference encoding, description formats, object openness and function handling.

The resulting architecture is therefore configurable at several points. Source paths determine the input program. The tsconfig.json determines TypeScript context. Root type and expose options determine which declarations enter the schema. Formatting settings determine representation and metadata. This gives the project more control than a fixed generator, but it also means a schema change can arise from compiler configuration, visibility policy or formatter settings, not only from a TypeScript declaration.

CLI Installation and First Schema Generation

The quickest documented first use is through npx. This invokes the package without first adding it as a local dependency. Replace the source glob and type name with values from the target project, then write the result to a file by adding the documented --out option.

bash
npx ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'

Without an output path, the CLI writes the schema to stdout. Quoting the glob prevents the shell from expanding it into a list of individual files. A project that keeps the generator in its own dependency graph can install it locally instead.

bash
npm install --save ts-json-schema-generator
./node_modules/.bin/ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'

The executable comes from the package's bin entry, bin/ts-json-schema-generator.js. On platforms with different path separators, such as Windows, the README says that the path expression may need adjustment.

The first integration check should confirm that the selected type exists and that the JSON output contains the expected root schema. If the project does not use the nearest tsconfig.json, pass --tsconfig explicitly. The documented option can also apply a dedicated configuration when schema generation requires different compiler options. This is especially relevant when a successful editor experience does not prove that the command is loading the intended TypeScript program.

Programmatic Generation from a Node.js Build Script

The package exports a factory-based API for callers that need to control when generation happens and where the result is stored. The README's example constructs a config object, creates a generator, selects its type argument and serializes the returned schema with JSON.stringify.

javascript
const tsj = require("ts-json-schema-generator");
const fs = require("fs");

const config = {
    path: "path/to/source/file",
    tsconfig: "path/to/tsconfig.json",
    type: "*"
};

const outputPath = "path/to/output/file";
const schema = tsj.createGenerator(config).createSchema(config.type);
const schemaString = JSON.stringify(schema, null, 2);
fs.writeFile(outputPath, schemaString, (err) => {
    if (err) throw err;
});

Running that script requires calling node main.js after adapting the paths and type. This approach fits a package build, release task or repository update workflow. It also avoids shell quoting concerns because the source path is passed as a JavaScript string.

The example uses CommonJS, which matches the package.json type field of commonjs. The package declares dist/index.js as its main entry and dist/index.d.ts as its type declaration entry. Repository maintenance includes a build script that runs tsc before publishing. The documentation does not describe a direct compiler API that can generate schemas from an already-created TypeScript Program, so existing integrations should not assume that the documented entry point supports every in-memory program configuration.

The API does more than print a string. createSchema returns a schema object that the caller can serialize. That distinction permits additional processing before writing the artifact, although the README does not document a schema validation step.

Exposure, References and Documentation Metadata

The default --expose value is export. This aligns generation with declarations intended for public use and avoids placing every unexported type into definitions. The option accepts all, none or export, giving a caller broader or narrower visibility policies. For a library whose public contract depends on selected internal helper types, the default can omit schema definitions needed later if the policy is not reconsidered.

References are enabled by default, while --no-ref-encode disables reference encoding. By default, generated schemas may contain a top-level reference arrangement, which --no-top-ref can suppress. These flags let an adopter change reference presentation, but they also create compatibility implications for downstream consumers that assume a particular schema structure. The README does not document an automatic migration path for changing between reference modes.

JSDoc support defaults to extended. The --jsDoc option can select none, basic or extended. Other switches add markdownDescription, include the raw comment as fullDescription and preserve individual function behavior as a comment by default. Functions can instead fail generation or be hidden. A schema containing runtime-callable functions needs an explicit policy because a validator cannot directly enforce that a JSON value originated from a TypeScript function.

Object policy is equally explicit. --additional-properties permits extra properties for objects without an index signature, while --strict-tuples rejects additional tuple items. --unstable leaves properties unsorted, and --minify removes formatting from the emitted schema. None of these options replaces an application decision about whether the produced contract should be strict or permissive.

Custom Formatters and the Limits of Generated Contracts

The extension interface targets projects that need representation rules beyond the built-in formatters. A custom SubTypeFormatter declares whether it supports a BaseType, supplies a Definition and reports child BaseType values. The README's function formatter example can represent a function as an object with an isFunction constant, although it also notes that a built-in function formatter exists.

This hook is useful when a project maps TypeScript-only constructs into a JSON representation that a JSON Schema validator can accept. The relevant question is not whether TypeScript compiles, but whether JSON instances can express the intended domain. A function member, for example, has no direct JSON value corresponding to executable behavior. Marking it hidden may fit a payload schema, while retaining it as a comment may preserve documentation without pretending that runtime behavior can be validated.

The project is the wrong tool when the required schema is not derived from TypeScript semantics, such as an OpenAPI document with operation paths, authentication declarations or endpoint metadata. It also fits poorly when schema generation must expose private declarations unconditionally, because export visibility is a documented part of the pipeline. Consumers that already maintain a complete, validated schema and gain nothing from TypeScript synchronization would gain little from adding this generator.

The README is also silent about schema dialect selection, annotation-version negotiation and automatic validation of the finished document. Do not infer support for those requirements from the package topics or from the term JSON Schema. Confirm them against the exact generated artifact and downstream validator before adoption.

Release Cadence, Defaults and Upgrade Review

The repository is not archived, and the last push was on 2026-10-01. The recent release entries are prerelease versions in the v2.9.1-next.18 series, dated 2026-07-02, 2026-07-01 and 2026-06-19. That release pattern calls for deliberate version checks rather than assuming that every prerelease carries the stability expectations of a final release.

The package metadata shown in package.json declares version 2.0.0 and identifies the project as CommonJS. It uses tsc for the build, and prepublishOnly runs npm run build. Upgrade review should therefore include the package lockfile, compiler compatibility and the generated schema diff. A change to defaults such as reference encoding, export exposure, JSDoc handling or sorting can alter committed output without changing application runtime code.

The project is licensed under MIT. That permits use and modification under the license's terms, but this review does not interpret those terms as legal advice. The source file also permits contributors to propose changes and directs them to the project's code of conduct. Based on the documented development setup, engineers can use npm run build to reproduce the TypeScript build and npm test to run the documented Node.js test command. Those scripts concern the repository's own source tree and are distinct from installing the published package in a consuming project.

Editorial conclusion

Adopt ts-json-schema-generator when schema output must remain tied to exported TypeScript types and can be generated through Node.js or a build script. Do not choose it when an unresolved schema artifact is sufficient or when unexported declarations must appear in the root definitions. Verify first that the intended root type resolves correctly under the selected tsconfig.json, especially when path mappings, separate compilation settings, JSDoc annotations or function members affect the expected output. Its CLI options and programmatic factory API provide concrete integration points, but output ownership and validation policy remain application decisions.

Frequently asked questions

How do I install ts-json-schema-generator?

The README documents npm install --save ts-json-schema-generator, followed by running ./node_modules/.bin/ts-json-schema-generator. It also documents npx ts-json-schema-generator when a local installation is unnecessary.

How do I generate a JSON Schema for one TypeScript type?

Pass a quoted source glob with --path and the type's name with --type. The documented example uses --type 'My.Type.Name', and output goes to stdout unless --out specifies a file.

Can ts-json-schema-generator use a custom tsconfig.json?

Yes. Pass the file path through --tsconfig. Without that option, the CLI searches the working directory and parent directories for tsconfig.json.

Does ts-json-schema-generator include unexported types by default?

No. The README states that unexported types, interfaces and enums are not exposed in definitions, and the default --expose setting is export. The option also accepts none and all.

Official sources

  1. Issues
  2. License: MIT
  3. README
  4. Releases
  5. vega/ts-json-schema-generator on GitHub
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/vega-ts-json-schema-generator.svg)](https://hysenlabs.com/projects/vega-ts-json-schema-generator)

Was this useful?