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 lets you infer 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>;// => Will infer the same type as above
Schemas can even be nested, as long as you don't forget the as const statement:
const catSchema = { ... } as const;const petSchema = { anyOf: [dogSchema, catSchema],} as const;type Pet = FromSchema<typeof petSchema>;// => Will work 🙌
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 widened as boolean). It is pure TypeScript and has zero impact on the compiled code.
If you don't mind impacting the compiled code, you can use the asConst util, which simply returns the schema while narrowing its inferred type.
import { asConst } from "json-schema-to-ts";const dogSchema = asConst({ type: "object", ...});type Dog = FromSchema<typeof dogSchema>;// => Will work as well 🙌
Since TS 4.9, you can also use the satisfies operator to benefit from type-checking and autocompletion:
import type { JSONSchema } from "json-schema-to-ts";const dogSchema = { // Type-checked and autocompleted 🙌 type: "object" ...} as const satisfies JSONSchematype Dog = FromSchema<typeof dogSchema>// => Still work 🙌
You can also use this with JSDocs by wrapping your schema in /** @type {const} @satisfies {import('json-schema-to-ts').JSONSchema} */ (...) like:
If you're looking for runtime validation with added types, libraries like yup, zod or runtypes may suit your needs while being easier to use!
On the other hand, JSON schemas have the benefit of being widely used, more versatile and reusable (swaggers, APIaaS...).
If you prefer to stick to them and can define your schemas in TS instead of JSON (importing JSONs as const is not available yet), then json-schema-to-ts is made for you:
✅ Schema validationFromSchema raises TS errors on invalid schemas, based on DefinitelyTyped's definitions
✨ No impact on compiled code: json-schema-to-ts only operates in type space. And after all, what's lighter than a dev-dependency?
🍸 DRYness: Less code means less embarrassing typos
🤝 Real-time consistency: See that string that you used instead of an enum? Or this additionalProperties you confused with additionalItems? Or forgot entirely? Well, json-schema-to-ts does!
🔧 Reliability: FromSchema is extensively tested against AJV, and covers all the use cases that can be handled by TS for now*
🏋️♂️ Help on complex schemas: Get complex schemas right first time with instantaneous typing feedbacks! For instance, it's not obvious the following schema can never be validated:
Defaulted properties (even optional ones) will be set as required in the resulting type. You can turn off this behavior by setting the keepDefaultedPropertiesOptional option to true:
Exclusions require heavy computations, that can sometimes be aborted by Typescript and end up in any inferred types. For this reason, they are not activated by default: You can opt-in with the parseNotKeyword option.
As some actionable keywords are not yet parsed, exclusions that resolve to never are granted the benefit of the doubt and omitted. For the moment, FromSchema assumes that you are not crafting unvalidatable exclusions.
const oddNumberSchema = { type: "number", not: { multipleOf: 2 },} as const;type OddNumber = FromSchema<typeof oddNumberSchema, { parseNotKeyword: true }>;// => should and will resolve to "number"const incorrectSchema = { type: "number", not: { bogus: "option" },} as const;type Incorrect = FromSchema<typeof incorrectSchema, { parseNotKeyword: true }>;// => should resolve to "never" but will still resolve to "number"
☝️ FromSchema computes the resulting type as (If ∩ Then) ∪ (¬If ∩ Else). While correct in theory, remember that the not keyword is not perfectly assimilated, which may become an issue in some complex schemas.
If you need to extend the JSON Schema spec with custom properties, use the ExtendedJSONSchema and FromExtendedSchema types to benefit from json-schema-to-ts:
import type { ExtendedJSONSchema, FromExtendedSchema } from "json-schema-to-ts";type CustomProps = { numberType: "int" | "float" | "bigInt";};const bigIntSchema = { type: "number", numberType: "bigInt", // 👇 Ensures mySchema is correct (includes extension)} as const satisfies ExtendedJSONSchema<CustomProps>;type BigInt = FromExtendedSchema< CustomProps, typeof bigIntSchema, { // 👇 Works very well with the deserialize option! deserialize: [ { pattern: { type: "number"; numberType: "bigInt"; }; output: bigint; }, ]; }>;
Typeguards
You can use FromSchema to implement your own typeguard:
import { FromSchema, Validator } from "json-schema-to-ts";// It's important to:// - Explicitely type your validator as Validator// - Use FromSchema as the default value of a 2nd generic firstconst validate: Validator = <S extends JSONSchema, T = FromSchema<S>>( schema: S, data: unknown): data is T => { const isDataValid: boolean = ... // Implement validation here return isDataValid;};const petSchema = { ... } as constlet data: unknown;if (validate(petSchema, data)) { const { name, ... } = data; // data is typed as Pet 🙌}
If needed, you can provide FromSchema options and additional validation options to the Validator type:
type FromSchemaOptions = { parseNotKeyword: true };type ValidationOptions = [{ fastValidate: boolean }]const validate: Validator<FromSchemaOptions, ValidationOptions> = < S extends JSONSchema, T = FromSchema<S, FromSchemaOptions>>( schema: S, data: unknown, ...validationOptions: ValidationOptions): data is T => { ... };
json-schema-to-ts also exposes two helpers to write type guards. They don't impact the code that you wrote (they simply return it), but turn it into type guards.
A validator is a function that receives a schema plus some data, and returns true if the data is valid compared to the schema, false otherwise.
You can use the wrapValidatorAsTypeGuard helper to turn validators into type guards. Here is an implementation with ajv:
import Ajv from "ajv";import { $Validator, wrapValidatorAsTypeGuard } from "json-schema-to-ts";const ajv = new Ajv();// The initial validator definition is up to you// ($Validator is prefixed with $ to differ from resulting type guard)const $validate: $Validator = (schema, data) => ajv.validate(schema, data);const validate = wrapValidatorAsTypeGuard($validate);const petSchema = { ... } as const;let data: unknown;if (validate(petSchema, data)) { const { name, ... } = data; // data is typed as Pet 🙌}
If needed, you can provide FromSchema options and additional validation options as generic types:
type FromSchemaOptions = { parseNotKeyword: true };type ValidationOptions = [{ fastValidate: boolean }]const $validate: $Validator<ValidationOptions> = ( schema, data, ...validationOptions // typed as ValidationOptions) => { ... };// validate will inherit from ValidationOptionsconst validate = wrapValidatorAsTypeGuard($validate);// with special FromSchemaOptions// (ValidationOptions needs to be re-provided)const validate = wrapValidatorAsTypeGuard< FromSchemaOptions, ValidationOptions>($validate);
Compilers
A compiler is a function that takes a schema as an input and returns a data validator for this schema as an output.
You can use the wrapCompilerAsTypeGuard helper to turn compilers into type guard builders. Here is an implementation with ajv:
import Ajv from "ajv";import { $Compiler, wrapCompilerAsTypeGuard } from "json-schema-to-ts";// The initial compiler definition is up to you// ($Compiler is prefixed with $ to differ from resulting type guard)const $compile: $Compiler = (schema) => ajv.compile(schema);const compile = wrapCompilerAsTypeGuard($compile);const petSchema = { ... } as const;const isPet = compile(petSchema);let data: unknown;if (isPet(data)) { const { name, ... } = data; // data is typed as Pet 🙌}
If needed, you can provide FromSchema options, additional compiling and validation options as generic types:
type FromSchemaOptions = { parseNotKeyword: true };type CompilingOptions = [{ fastCompile: boolean }];type ValidationOptions = [{ fastValidate: boolean }];const $compile: $Compiler<CompilingOptions, ValidationOptions> = ( schema, ...compilingOptions // typed as CompilingOptions) => { ... return ( data, ...validationOptions // typed as ValidationOptions ) => { ... };};// compile will inherit from all optionsconst compile = wrapCompilerAsTypeGuard($compile);// with special FromSchemaOptions// (options need to be re-provided)const compile = wrapCompilerAsTypeGuard< FromSchemaOptions, CompilingOptions, ValidationOptions>($compile);