json-schema-to-typescript vs typescript-json-schema
Generating TypeScript Types from JSON Schemas and Vice Versa
json-schema-to-typescripttypescript-json-schema

Generating TypeScript Types from JSON Schemas and Vice Versa

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
json-schema-to-typescript03,336201 kB2002 years agoMIT
typescript-json-schema03,266260 kB189a month agoBSD-3-Clause

json-schema-to-typescript vs typescript-json-schema: Direction Matters

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.

🔄 Core Direction: Input vs Output

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

🛠️ Handling Complex Types

Both tools handle real-world complexity, but differently based on their direction.

Optional Properties & Unions

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"]
    }
  }
}

References and Reusability

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.

⚙️ Integration with Build Systems

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.

🧪 Runtime Validation Scenarios

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.

📁 File I/O and Programmatic Use

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);

🚫 Common Pitfalls

  • 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.

✅ When They Work Together

In mature architectures, you might use both:

  1. Backend defines UserDTO in TypeScript.
  2. typescript-json-schema generates user.schema.json.
  3. Frontend consumes user.schema.json via json-schema-to-typescript to produce User.ts.
  4. Both sides validate payloads at runtime using the same schema.

This creates a closed loop of type safety across the stack.

📊 Summary: Key Differences

Aspectjson-schema-to-typescripttypescript-json-schema
Primary DirectionJSON Schema → TypeScriptTypeScript → JSON Schema
InputJSON Schema file or objectTypeScript source files + tsconfig
Output.ts file with interfaces/typesJSON Schema object or file
Best ForConsuming external API contractsPublishing schemas from TS codebase
Compiler DependencyNoneRequires TypeScript compiler
Handles $refYes (resolves during compile)N/A (starts from TS, not JSON Schema)
Handles TS GenericsNo (input is JSON Schema)Limited support

💡 Final Guidance

Ask yourself: Where does my source of truth live?

  • If it’s a JSON Schema document (from OpenAPI, Postman, or a spec), reach for json-schema-to-typescript.
  • If it’s TypeScript code (your own models or DTOs), use 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.

How to Choose: json-schema-to-typescript vs typescript-json-schema

  • json-schema-to-typescript:

    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.

  • typescript-json-schema:

    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.

README for json-schema-to-typescript

json-schema-to-typescript Build Status npm mit node

Compile JSON Schema to TypeScript typings.

Example

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";
}

Installation

npm install json-schema-to-typescript

Usage

json-schema-to-typescript is easy to use via the CLI, or programmatically.

CLI

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

API

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.

Options

compileFromFile and compile accept options as their last argument (all keys are optional):

keytypedefaultdescription
additionalPropertiesbooleantrueDefault value for additionalProperties, when it is not explicitly set
bannerCommentstring"/* 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 | undefinedundefinedCustom function to provide a type name for a given schema
cwdstringprocess.cwd()Root directory for resolving $refs
declareExternallyReferencedbooleantrueDeclare external schemas referenced via $ref?
enableConstEnumsbooleantruePrepend enums with const?
inferStringEnumKeysFromValuesbooleanfalseCreate enums from JSON enums with eponymous keys
formatbooleantrueFormat code? Set this to false to improve performance.
ignoreMinAndMaxItemsbooleanfalseIgnore maxItems and minItems for array types, preventing tuples being generated.
maxItemsnumber20Maximum 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.
strictIndexSignaturesbooleanfalseAppend all index signatures with | undefined so that they are strictly typed.
styleobject{ bracketSpacing: false, printWidth: 120, semi: true, singleQuote: false, tabWidth: 2, trailingComma: 'none', useTabs: false }A Prettier configuration
unknownAnybooleantrueUse unknown instead of any where possible
unreachableDefinitionsbooleanfalseGenerates code for $defs that aren't referenced by the schema.
$refOptionsobject{}$RefParser Options, used when resolving $refs

Tests

$ npm test

Features

  • title => interface
  • Primitive types:
    • array
    • homogeneous array
    • boolean
    • integer
    • number
    • null
    • object
    • string
    • homogeneous enum
    • heterogeneous enum
  • Non/extensible interfaces
  • Custom JSON-schema extensions
  • Nested properties
  • Schema definitions
  • Schema references
  • Local (filesystem) schema references
  • External (network) schema references
  • Add support for running in browser
  • default interface name
  • infer unnamed interface name from filename
  • deprecated
  • allOf ("intersection")
  • anyOf ("union")
  • oneOf (treated like anyOf)
  • maxItems (eg)
  • minItems (eg)
  • additionalProperties of type
  • patternProperties (partial support)
  • extends
  • required properties on objects (eg)
  • validateRequired (eg)
  • literal objects in enum (eg)
  • referencing schema by id (eg)
  • custom typescript types via tsType

Custom schema properties:

  • tsType: 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).

Not expressible in TypeScript:

FAQ

JSON-Schema-to-TypeScript is crashing on my giant file. What can I do?

Prettier is known to run slowly on really big files. To skip formatting and improve performance, set the format option to false.

Further Reading

Who uses JSON-Schema-to-TypeScript?