json-schema-to-typescript and typescript-json-schema are complementary tools in the TypeScript ecosystem for bridging JSON Schema and TypeScript type definitions. json-schema-to-typescript compiles JSON Schema documents into idiomatic TypeScript interfaces or types, enabling strong typing for APIs, configuration files, or data validation layers. In contrast, typescript-json-schema does the reverse: it analyzes TypeScript source code using the TypeScript compiler API to extract type information and generate corresponding JSON Schema definitions. Both are commonly used in full-stack applications where schema consistency between frontend and backend is critical, such as in OpenAPI/Swagger integrations, form validation, or runtime type checking with libraries like Ajv.
At first glance, both json-schema-to-typescript and typescript-json-schema deal with the same two worlds: JSON Schema and TypeScript. But they solve opposite problems. Understanding which direction you’re moving in—schema → TS or TS → schema—is the key to picking the right tool.
json-schema-to-typescript takes a JSON Schema object and outputs TypeScript type definitions.
// Input: JSON Schema (e.g., user.schema.json)
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number" }
},
"required": ["name"]
}
// Output: Generated TypeScript
interface User {
name: string;
age?: number;
}
You’d typically run this as a build step:
// build-types.js
const fs = require('fs');
const { compile } = require('json-schema-to-typescript');
compile(fs.readFileSync('user.schema.json', 'utf8'), 'User')
.then(ts => fs.writeFileSync('user.ts', ts));
typescript-json-schema takes TypeScript source files and outputs a JSON Schema object.
// Input: TypeScript (e.g., models.ts)
export interface User {
name: string;
age?: number;
}
You generate schema via CLI or API:
// build-schema.js
const { generateSchema } = require('typescript-json-schema');
const program = require('typescript').createProgram(['models.ts'], {});
const schema = generateSchema(program, 'User');
// schema is now a JSON Schema object
Or via command line:
npx typescript-json-schema tsconfig.json User --out user.schema.json
Both tools handle real-world complexity, but differently based on their direction.
json-schema-to-typescript maps JSON Schema’s required array and anyOf/oneOf to optional properties and union types:
// schema.json
{
"type": "object",
"properties": {
"status": { "enum": ["active", "inactive"] }
},
"required": []
}
Becomes:
interface MyObject {
status?: "active" | "inactive";
}
typescript-json-schema converts TypeScript unions and optional fields back into equivalent JSON Schema:
// models.ts
interface ApiResponse {
data?: string | number;
error?: { message: string };
}
Generates:
{
"type": "object",
"properties": {
"data": { "anyOf": [{ "type": "string" }, { "type": "number" }] },
"error": {
"type": "object",
"properties": { "message": { "type": "string" } },
"required": ["message"]
}
}
}
json-schema-to-typescript resolves $ref pointers during compilation:
// main.schema.json
{
"$ref": "./definitions.json#/User"
}
It inlines or generates separate interfaces based on options, producing flat or modular TS output.
typescript-json-schema follows TypeScript imports and type aliases:
// user.ts
import { Address } from './shared';
interface User {
address: Address;
}
The resulting JSON Schema includes a definition for Address and references it correctly if enabled.
json-schema-to-typescript is designed for frontend consumption. You often run it once during setup or as part of a CI pipeline to keep your types in sync with a backend schema. The output is meant to be committed to source control.
typescript-json-schema integrates tightly with the TypeScript compiler. It requires a valid tsconfig.json and parses your actual codebase. This makes it powerful for generating up-to-date schemas from evolving domain models, especially in monorepos.
Suppose you use Ajv for runtime validation in your app.
If your team owns the backend and defines types in TypeScript, use typescript-json-schema to emit JSON Schema, then share that schema with the frontend for validation.
If you’re a frontend team consuming a third-party API that publishes an OpenAPI spec (which includes JSON Schema), use json-schema-to-typescript to turn those schemas into TypeScript interfaces for Axios or Fetch wrappers.
Both support programmatic usage, but their APIs reflect their purpose.
json-schema-to-typescript:
const { compileFromFile } = require('json-schema-to-typescript');
compileFromFile('api.schema.json', {
cwd: './schemas',
bannerComment: ''
}).then(ts => console.log(ts));
typescript-json-schema:
const { createProgram, generateSchema } = require('typescript-json-schema');
const program = createProgram(['src/models.ts']);
const settings = { required: true };
const schema = generateSchema(program, 'Order', settings);
json-schema-to-typescript cannot infer types that don’t exist in the schema. If your JSON Schema lacks required fields, everything becomes optional—even if your API actually requires them.
typescript-json-schema may struggle with highly dynamic or conditional types (e.g., Exclude<T, U> with complex generics). It works best with concrete interfaces and type aliases.
In mature architectures, you might use both:
UserDTO in TypeScript.typescript-json-schema generates user.schema.json.user.schema.json via json-schema-to-typescript to produce User.ts.This creates a closed loop of type safety across the stack.
| Aspect | json-schema-to-typescript | typescript-json-schema |
|---|---|---|
| Primary Direction | JSON Schema → TypeScript | TypeScript → JSON Schema |
| Input | JSON Schema file or object | TypeScript source files + tsconfig |
| Output | .ts file with interfaces/types | JSON Schema object or file |
| Best For | Consuming external API contracts | Publishing schemas from TS codebase |
| Compiler Dependency | None | Requires TypeScript compiler |
| Handles $ref | Yes (resolves during compile) | N/A (starts from TS, not JSON Schema) |
| Handles TS Generics | No (input is JSON Schema) | Limited support |
Ask yourself: Where does my source of truth live?
json-schema-to-typescript.typescript-json-schema.Don’t try to force one tool to do the other’s job — they’re optimized for opposite workflows. Used correctly, either can eliminate entire classes of bugs caused by schema drift between client and server.
Choose json-schema-to-typescript when you start with a JSON Schema (e.g., from an OpenAPI spec or a backend contract) and need to generate clean, maintainable TypeScript types for your frontend. It’s ideal for frontend teams consuming well-defined external schemas and wanting compile-time safety without writing types manually. The tool supports advanced JSON Schema features like $ref, allOf/anyOf, and custom formatting, and produces human-readable output suitable for version control.
Choose typescript-json-schema when your source of truth is TypeScript code—such as domain models or DTOs—and you need to emit JSON Schema for documentation, validation, or interoperability with non-TypeScript systems. This is common in monorepos where backend logic defines types in TS, and the frontend or API gateway needs schema artifacts. It leverages the TypeScript compiler directly, so it accurately reflects complex types including generics, mapped types, and conditional logic.
Compile JSON Schema to TypeScript typings.
Check out the live demo.
Input:
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"hairColor": {
"enum": ["black", "brown", "blue"],
"type": "string"
}
},
"additionalProperties": false,
"required": ["firstName", "lastName"]
}
Output:
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
hairColor?: "black" | "brown" | "blue";
}
npm install json-schema-to-typescript
json-schema-to-typescript is easy to use via the CLI, or programmatically.
First make the CLI available using one of the following options:
# install locally, then use `npx json2ts`
npm install json-schema-to-typescript
# or install globally, then use `json2ts`
npm install json-schema-to-typescript --global
# or install to npm cache, then use `npx --package=json-schema-to-typescript json2ts`
# (you don't need to run an install command first)
Then, use the CLI to convert JSON files to TypeScript typings:
cat foo.json | json2ts > foo.d.ts
# or
json2ts foo.json > foo.d.ts
# or
json2ts foo.yaml foo.d.ts
# or
json2ts --input foo.json --output foo.d.ts
# or
json2ts -i foo.json -o foo.d.ts
# or (quote globs so that your shell doesn't expand them)
json2ts -i 'schemas/**/*.json'
# or
json2ts -i schemas/ -o types/
You can pass any of the options described below (including style options) as CLI flags. Boolean values can be set to false using the no- prefix.
# generate code for definitions that aren't referenced
json2ts -i foo.json -o foo.d.ts --unreachableDefinitions
# use single quotes and disable trailing semicolons
json2ts -i foo.json -o foo.d.ts --style.singleQuote --no-style.semi
To invoke json-schema-to-typescript from your TypeScript or JavaScript program, import it and call compile or compileFromFile.
import { compile, compileFromFile } from 'json-schema-to-typescript'
// compile from file
compileFromFile('foo.json')
.then(ts => fs.writeFileSync('foo.d.ts', ts))
// or, compile a JS object
let mySchema = {
properties: [...]
}
compile(mySchema, 'MySchema')
.then(ts => ...)
See server demo and browser demo for full examples.
compileFromFile and compile accept options as their last argument (all keys are optional):
| key | type | default | description |
|---|---|---|---|
| additionalProperties | boolean | true | Default value for additionalProperties, when it is not explicitly set |
| bannerComment | string | "/* eslint-disable */\n/**\n* This file was automatically generated by json-schema-to-typescript.\n* DO NOT MODIFY IT BY HAND. Instead, modify the source JSON Schema file,\n* and run json-schema-to-typescript to regenerate this file.\n*/" | Disclaimer comment prepended to the top of each generated file |
| customName | (LinkedJSONSchema, string | undefined) => string | undefined | undefined | Custom function to provide a type name for a given schema |
| cwd | string | process.cwd() | Root directory for resolving $refs |
| declareExternallyReferenced | boolean | true | Declare external schemas referenced via $ref? |
| enableConstEnums | boolean | true | Prepend enums with const? |
| inferStringEnumKeysFromValues | boolean | false | Create enums from JSON enums with eponymous keys |
| format | boolean | true | Format code? Set this to false to improve performance. |
| ignoreMinAndMaxItems | boolean | false | Ignore maxItems and minItems for array types, preventing tuples being generated. |
| maxItems | number | 20 | Maximum number of unioned tuples to emit when representing bounded-size array types, before falling back to emitting unbounded arrays. Increase this to improve precision of emitted types, decrease it to improve performance, or set it to -1 to ignore maxItems. |
| strictIndexSignatures | boolean | false | Append all index signatures with | undefined so that they are strictly typed. |
| style | object | { bracketSpacing: false, printWidth: 120, semi: true, singleQuote: false, tabWidth: 2, trailingComma: 'none', useTabs: false } | A Prettier configuration |
| unknownAny | boolean | true | Use unknown instead of any where possible |
| unreachableDefinitions | boolean | false | Generates code for $defs that aren't referenced by the schema. |
| $refOptions | object | {} | $RefParser Options, used when resolving $refs |
$ npm test
title => interfacedeprecatedallOf ("intersection")anyOf ("union")oneOf (treated like anyOf)maxItems (eg)minItems (eg)additionalProperties of typepatternProperties (partial support)extendsrequired properties on objects (eg)validateRequired (eg)tsTypetsType: Overrides the type that's generated from the schema. Useful for forcing a type to any or when using non-standard JSON schema extensions (eg).tsEnumNames: Overrides the names used for the elements in an enum. Can also be used to create string enums (eg).dependencies (single, multiple)divisibleBy (eg)format (eg)multipleOf (eg)maximum (eg)minimum (eg)maxProperties (eg)minProperties (eg)not/disallowoneOf ("xor", use anyOf instead)pattern (string, regex)uniqueItems (eg)Prettier is known to run slowly on really big files. To skip formatting and improve performance, set the format option to false.