What is json-schema-to-ts?
The json-schema-to-ts npm package is a utility that converts JSON Schema definitions into TypeScript types. This allows developers to ensure type safety and consistency between their JSON data and TypeScript code.
What are json-schema-to-ts's main functionalities?
Convert JSON Schema to TypeScript Types
This feature allows you to convert a JSON Schema into a TypeScript type. The `FromSchema` utility type takes a JSON Schema object and infers the corresponding TypeScript type.
import { FromSchema } from 'json-schema-to-ts';
const userSchema = {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
age: { type: 'number' }
},
required: ['id', 'name']
} as const;
type User = FromSchema<typeof userSchema>;
const user: User = {
id: '123',
name: 'John Doe',
age: 30
};
Type Validation
This feature ensures that the TypeScript types derived from JSON Schema are validated at compile time, reducing runtime errors and improving code reliability.
import { FromSchema } from 'json-schema-to-ts';
const productSchema = {
type: 'object',
properties: {
productId: { type: 'string' },
price: { type: 'number' }
},
required: ['productId', 'price']
} as const;
type Product = FromSchema<typeof productSchema>;
const product: Product = {
productId: 'abc123',
price: 19.99
};
Other packages similar to json-schema-to-ts
typescript-json-schema
The typescript-json-schema package generates JSON Schema from your TypeScript types. It works in the opposite direction compared to json-schema-to-ts, which converts JSON Schema to TypeScript types. This package is useful if you start with TypeScript types and need to generate JSON Schema for validation or documentation purposes.
ajv
Ajv is a JSON Schema validator that can also generate TypeScript types from JSON Schema using additional plugins. While its primary focus is on validation, it offers similar functionality to json-schema-to-ts when combined with the appropriate plugins.
zod
Zod is a TypeScript-first schema declaration and validation library. It allows you to define schemas in TypeScript and infer types from them. While it doesn't convert JSON Schema to TypeScript types directly, it provides a similar type-safe experience for defining and validating data structures.
Stop typing twice 🙅♂️
A lot of projects use JSON schemas for runtime data validation along with TypeScript for static type checking.
Their code may look like this:
const dogSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
hobbies: { type: "array", items: { type: "string" } },
favoriteFood: { enum: ["pizza", "taco", "fries"] },
},
required: ["name", "age"],
};
type Dog = {
name: string;
age: number;
hobbies?: string[];
favoriteFood?: "pizza" | "taco" | "fries";
};
Both objects carry similar if not exactly the same information. This is a code duplication that can annoy developers and introduce bugs if not properly maintained.
That's when json-schema-to-ts
comes to the rescue 💪
FromSchema
The FromSchema
method allows infering TS types directly from JSON schemas:
import { FromSchema } from "json-schema-to-ts";
const dogSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
hobbies: { type: "array", items: { type: "string" } },
favoriteFood: { enum: ["pizza", "taco", "fries"] },
},
required: ["name", "age"],
} as const;
type Dog = FromSchema<typeof dogSchema>;
Schemas can even be nested, as long as you don't forget the as const
statement:
const catSchema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
favoriteThings: { enum: ["playing", "sleeping", "sleepingMore"] },
},
required: ["name", "age"],
} as const;
const petSchema = {
anyOf: [dogSchema, catSchema],
} as const;
type Pet = FromSchema<typeof petSchema>;
Note: The as const
statement is used so that TypeScript takes the schema definition to the word (e.g. true is interpreted as the true constant and not as boolean). It is pure TypeScript and has zero impact on the compiled code.
Docs
Installation
npm install --save-dev json-schema-to-ts
yarn add --dev json-schema-to-ts
Use cases
Litterals
const litteralSchema = {
type: "null",
} as const;
type Litteral = FromSchema<typeof litteralSchema>;
Objects
const objectSchema = {
type: "object",
properties: {
foo: { type: "string" },
bar: { type: "number" },
},
required: ["foo"],
} as const;
type Object = FromSchema<typeof objectSchema>;
FromSchema
partially supports the use of the additionalProperties
and patternProperties
keyword:
- Contrary to the specifications,
additionalProperties
is considered false
by default for clearer typings. Set its value to true
to signal that additional properties can be used:
const additionalPropertiesSchema = {
...objectSchema,
additionalProperties: true,
} as const;
type Object = FromSchema<typeof additionalPropertiesSchema>;
- Used on their own, typed
additionalProperties
and/or patternProperties
are supported:
const typedValuesSchema = {
type: "object",
additionalProperties: {
type: "boolean",
},
} as const;
type Object = FromSchema<typeof typedValuesSchema>;
const patternSchema = {
type: "object",
patternProperties: {
"^S": { type: "string" },
"^I": { type: "integer" },
},
} as const;
type Object = FromSchema<typeof patternSchema>;
- However, due to TypeScript limitations, when used in combination with the
properties
keyword, extra properties will always be typed as any
to avoid conflicts with base properties.
Arrays
const arraySchema = {
type: "array",
items: { type: "string" },
} as const;
type Array = FromSchema<typeof arraySchema>;
Tuples
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
FromSchema
supports the additionalItems
keyword:
- You can deny additional items:
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
additionalItems: false,
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
- Or specify a type for additional items:
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
additionalItems: { type: "number" },
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
FromSchema
also supports the minItems
and maxItems
keyword:
const tupleSchema = {
type: "array",
items: [{ type: "boolean" }, { type: "string" }],
minItems: 1,
maxItems: 2,
} as const;
type Tuple = FromSchema<typeof tupleSchema>;
Multiple Types
const multipleTypesSchema = {
type: ["null", "string"],
} as const;
type Tuple = FromSchema<typeof multipleTypesSchema>;
Other properties like required
or additionalItems
will also work 🙌
const multipleTypesSchema = {
type: ["array", "object"],
items: [{ type: "string" }],
additionalItems: false,
properties: {
name: { type: "string" },
age: { type: "number" },
},
required: ["name"],
} as const;
type Tuple = FromSchema<typeof multipleTypesSchema>;
Const
const fooSchema = {
const: "foo",
} as const;
type Foo = FromSchema<typeof fooSchema>;
Enums
const enumSchema = {
enum: [true, 42, { foo: "bar" }],
} as const;
type Enum = FromSchema<typeof enumSchema>;
enum
can be used concurrently with type
.
const enumSchema = {
type: "string",
enum: ["foo", "bar", { foo: "bar" }],
} as const;
type Enum = FromSchema<typeof enumSchema>;
AnyOf
const anyOfSchema = {
anyOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
},
],
} as const;
type AnyOf = FromSchema<typeof fooSchema>;