JSON 17 ๐ Generating TypeScript Types from JSON Schema
The JSON Schema is the runtime contract, and the TypeScript type is the compile-time contract. The two must agree, and the generation is the mechanism that keeps them from drifting. The json-schema-to-typescript package is the tool that reads a JSON Schema and writes the TypeScript interfaces and type aliases that describe the same data . The generated file is the compile-time artifact, and the schema is the runtime source. The generation is the bridge between the two.
The package’s CLI is json2ts, and it accepts the input from a file, a glob, or the stdin. The json2ts foo.json > foo.d.ts is the simplest invocation, and the json2ts -i 'schemas/**/*.json' -o types/ is the batch form . The API is the compile and the compileFromFile functions, and the two accept the schema and the options. The compileFromFile reads the schema from the disk, and the compile takes the schema object . The two are the same mechanism, and the choice is the input source.
The options are the second half of the tool. The additionalProperties: false is the option that omits the index signature, and the unknownAny: true is the option that uses unknown instead of any . The declareExternallyReferenced is the option that declares the external schemas, and the unreachableDefinitions is the option that generates the code for the definitions that are not referenced . The options are the mechanism that shapes the output, and the shape is the difference between the usable types and the noisy ones.
Key point: The json-schema-to-typescript package generates the TypeScript types from a JSON Schema. The CLI is json2ts, and the API is the compile and the compileFromFile functions. The additionalProperties: false is the option that omits the index signature, and the unknownAny: true is the option that uses unknown. The generated types are the compile-time contract, and the schema is the runtime source.
Why the generation exists
The drift problem. A project that writes the schema and the TypeScript type separately has two sources of truth. The schema is the runtime validation, and the type is the compile-time check. The two drift, and the drift is the bug: the schema accepts a field that the type does not have, or the type requires a field that the schema does not. The generation is the mechanism that derives the type from the schema, and the derivation is the reason the two cannot disagree .
The hand-written type problem. A hand-written type is the guess about the schema. The developer reads the schema and writes the interface, and the reading is the place where the mistakes happen. The additionalProperties is the common miss: the schema allows the extra properties, and the hand-written type omits the index signature, and the extra properties are the runtime error. The generation is the mechanism that reads the schema the same way the validator does, and the reading is the reason the type is accurate.
The external-schema problem. A project consumes the external API that publishes the OpenAPI spec or the JSON Schema. The schema is the contract, and the types are the local representation. The generation is the mechanism that produces the local types from the external contract, and the production is the reason the frontend can use the API without the manual type writing . The schema is the source, and the type is the derived artifact.
The $ref problem. A schema with the $ref references has the shared definitions. The generation resolves the references, and the resolution is the mechanism that produces the shared types. The declareExternallyReferenced is the option that declares the external schemas, and the declaration is the reason the referenced types are available .
The style problem. The generated type can be the interface or the type, the enum or the union, and the style is the project’s convention. The enableConstEnums is the option that controls the enum style, and the style object is the Prettier configuration that formats the output . The style is the mechanism that makes the generated code match the project’s conventions.
a. The CLI and the basic generation
The CLI is the json2ts command, and the input is the file, the glob, or the stdin. The output is the TypeScript declarations.
# The basic generation
json2ts foo.json > foo.d.ts
# The explicit input and output
json2ts -i foo.json -o foo.d.ts
# The glob input
json2ts -i 'schemas/**/*.json' -o types/
# The stdin input
cat foo.json | json2ts > foo.d.ts
The json2ts foo.json > foo.d.ts is the mechanism that reads the schema and writes the type. The -i and the -o flags are the explicit form, and the glob form is the batch mechanism . The stdin form is the pipe mechanism, and the pipe is the reason the CLI can be used in the scripts.
// The input schema
{
"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"]
}
// The generated output
export interface ExampleSchema {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
hairColor?: "black" | "brown" | "blue";
}
The generated interface has the required fields as the non-optional, and the optional fields as the optional. The age is the optional number, and the hairColor is the optional union of the enum values. The additionalProperties: false is the option that omits the index signature, and the omission is the reason the interface has only the declared fields .
b. The API and the options
The API is the compile and the compileFromFile functions. The compileFromFile reads the schema from the disk, and the compile takes the schema object. The two accept the options as the last argument.
// The compileFromFile API
import { compileFromFile } from "json-schema-to-typescript";
import { writeFileSync } from "node:fs";
const types = await compileFromFile("schema.json", {
// The additionalProperties: false omits the index signature.
additionalProperties: false,
// The unknownAny: true uses unknown instead of any.
unknownAny: true,
// The declareExternallyReferenced declares the external schemas.
declareExternallyReferenced: true,
});
writeFileSync("schema.d.ts", types);
The compileFromFile("schema.json", options) is the mechanism that reads the file and generates the types. The additionalProperties: false is the option that makes the output strict, and the unknownAny: true is the option that uses the unknown type . The declareExternallyReferenced: true is the option that declares the external schemas, and the declaration is the reason the referenced types are available.
// The compile API
import { compile } from "json-schema-to-typescript";
const schema = {
type: "object",
properties: {
name: { type: "string" },
},
required: ["name"],
};
const types = await compile(schema, "User", {
additionalProperties: false,
});
// The types is the string of the TypeScript declarations.
The compile(schema, "User", options) is the mechanism that takes the schema object and the type name. The "User" is the name of the generated interface, and the name is the mechanism that makes the output readable . The compile is the API form for the in-memory schema, and the compileFromFile is the file form.
Complete Example Session
// ============================================
// PART 1: THE INPUT SCHEMA
// ============================================
const userSchema = {
title: "User",
type: "object",
properties: {
id: { type: "integer", minimum: 1 },
name: { type: "string" },
email: { type: "string", format: "email" },
role: { enum: ["admin", "user", "guest"], type: "string" },
},
required: ["id", "name", "email"],
additionalProperties: false,
};
// ============================================
// PART 2: THE COMPILE FROM FILE
// ============================================
import { compileFromFile } from "json-schema-to-typescript";
const types = await compileFromFile("user.schema.json", {
additionalProperties: false,
unknownAny: true,
});
// ============================================
// PART 3: THE COMPILE FROM OBJECT
// ============================================
import { compile } from "json-schema-to-typescript";
const typesFromObject = await compile(userSchema, "User", {
additionalProperties: false,
});
// ============================================
// PART 4: THE GENERATED OUTPUT
// ============================================
// export interface User {
// id: number;
// name: string;
// email: string;
// role?: "admin" | "user" | "guest";
// }
// The required fields are non-optional.
// The enum is the union.
// ============================================
// PART 5: THE ADDITIONAL PROPERTIES OPTION
// ============================================
// The additionalProperties: false omits the index signature.
// The default is true, which adds the [k: string]: unknown.
// ============================================
// PART 6: THE UNKNOWN ANY OPTION
// ============================================
// The unknownAny: true uses unknown instead of any.
// The default is true.
// ============================================
// PART 7: THE DECLARE EXTERNALLY REFERENCED OPTION
// ============================================
// The declareExternallyReferenced: true declares the external schemas.
// The referenced types are available.
// ============================================
// PART 8: THE UNREACHABLE DEFINITIONS OPTION
// ============================================
// The unreachableDefinitions: true generates the unreferenced $defs.
// ============================================
// PART 9: THE CLI
// ============================================
// json2ts -i user.schema.json -o user.d.ts
// The CLI is the same generation.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The json-schema-to-typescript is installed.
// [ ] The compile or the compileFromFile is used.
// [ ] The additionalProperties: false is set.
// [ ] The unknownAny: true is set.
// [ ] The generated types are committed or generated in the build.
The ten parts covered the input schema, the compile from file, the compile from object, the generated output, the additional properties option, the unknown any option, the declare externally referenced option, the unreachable definitions option, the CLI, and the checklist. The through-line is that the schema is the source, and the generation is the derivation.
Quick Reference
The CLI
| Command | Purpose |
|---|---|
json2ts foo.json > foo.d.ts | The basic generation |
json2ts -i foo.json -o foo.d.ts | The explicit input and output |
json2ts -i 'schemas/**/*.json' | The glob input |
The API
| Function | Purpose |
|---|---|
compile(schema, name, options) | The in-memory schema |
compileFromFile(path, options) | The file schema |
The options
| Option | Default | Purpose |
|---|---|---|
additionalProperties | true | The index signature |
unknownAny | true | The unknown type |
declareExternallyReferenced | true | The external schema declaration |
unreachableDefinitions | false | The unreferenced definitions |
enableConstEnums | true | The const enum |
The generated output
| Schema | TypeScript |
|---|---|
| The required field | The non-optional property |
| The optional field | The optional property |
| The enum | The union of the literals |
| The integer | The number |
Best Practices
โ Do This:
# Use the additionalProperties: false for the strict types
json2ts -i schema.json -o types.d.ts --additionalProperties false // โ
// Use the compileFromFile for the file schemas
const types = await compileFromFile("schema.json", { additionalProperties: false }); // โ
โ Don’t Do This:
# Assume the default additionalProperties is false
json2ts -i schema.json -o types.d.ts // the index signature is added // โ
// Hand-write the type that mirrors the schema
interface User { name: string; } // the drift risk // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The index signature is unexpected | The additionalProperties defaults to true | Set the additionalProperties: false |
The type is any | The unknownAny is false | Set the unknownAny: true |
| The referenced type is missing | The declareExternallyReferenced is false | Set the option to true |
| The unreferenced definition is missing | The unreachableDefinitions is false | Set the option to true |
Real-World Examples
1. The basic CLI
json2ts schema.json > types.d.ts
2. The explicit CLI
json2ts -i schema.json -o types.d.ts
3. The compile API
const types = await compile(schema, "User");
4. The compileFromFile API
const types = await compileFromFile("schema.json");
5. The additionalProperties option
{ additionalProperties: false }
6. The unknownAny option
{ unknownAny: true }
7. The generated interface
export interface User { id: number; name: string; }
8. The enum union
role?: "admin" | "user" | "guest";
9. The glob input
json2ts -i 'schemas/**/*.json' -o types/
10. The stdin input
cat schema.json | json2ts > types.d.ts
Visual
The Generation Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE GENERATION FLOW โ
โ โ
โ The JSON Schema โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ json-schema-to- โ The generation โ
โ โ typescript โ โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The TypeScript โ The compile-time contract โ
โ โ types โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The additionalProperties Option
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE additionalProperties OPTION โ
โ โ
โ The default (true): โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ export interface โ The index signature is added โ
โ โ User { โ โ
โ โ [k: string]: unknownโ โ
โ โ } โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ The false: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ export interface โ The only declared fields โ
โ โ User { โ โ
โ โ name: string; โ โ
โ โ } โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Schema and the Type
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE SCHEMA AND THE TYPE โ
โ โ
โ The schema: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ required: ["name"] โ The name is required โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ The type: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ name: string; โ The non-optional property โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| The package | json-schema-to-typescript |
| The CLI | json2ts |
| The API | compile and compileFromFile |
The additionalProperties | The index signature control |
The unknownAny | The unknown vs any |
The declareExternallyReferenced | The external schema declaration |
The unreachableDefinitions | The unreferenced definitions |
Key takeaways:
- The
json-schema-to-typescriptpackage generates the TypeScript types from a JSON Schema. The CLI isjson2ts, and the API is thecompileand thecompileFromFilefunctions. The schema is the runtime contract, and the generated types are the compile-time contract . - The
additionalProperties: falseis the option that omits the index signature. The default istrue, which adds the[k: string]: unknownto the generated interface. The strict mode is the option that makes the output match the schema’s strictness . - The
unknownAny: trueis the option that usesunknowninstead ofany. The default istrue, and the option is the mechanism that keeps the generated types safe. - The
declareExternallyReferencedand theunreachableDefinitionsare the reference options. The first declares the external schemas, and the second generates the code for the definitions that are not referenced . - The generated types are the compile-time contract, and the schema is the runtime source. The generation is the mechanism that keeps the two from drifting, and the drift is the bug that the generation removes .
Remember: The JSON Schema to TypeScript generation is the bridge between the runtime and the compile time. The json-schema-to-typescript package is the tool, and the json2ts is the CLI. The additionalProperties: false is the strict mode, and the unknownAny: true is the safe mode. The schema is the source, and the type is the derived artifact. The generation is the mechanism that keeps them aligned.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!