Skip to content

sebastian-fredriksson-bernholtz/json-schema-to-ts

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

If you use this repo, star it ✨

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

Why use json-schema-to-ts?

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 validation FromSchema 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
  • 🀝 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:
const addressSchema = {
  type: "object",
  allOf: [
    {
      properties: {
        street: { type: "string" },
        city: { type: "string" },
        state: { type: "string" },
      },
      required: ["street", "city", "state"],
    },
    {
      properties: {
        type: { enum: ["residential", "business"] },
      },
    },
  ],
  additionalProperties: false,
} as const;

But it is with FromSchema!

type Address = FromSchema<typeof addressSchema>;
// => never πŸ™Œ

*If json-schema-to-ts misses one of your use case, feel free to open an issue πŸ€—

Table of content

Installation

# npm
npm install --save-dev json-schema-to-ts

# yarn
yarn add --dev json-schema-to-ts

json-schema-to-ts requires TypeScript 3.3+. Activating strictNullChecks or using strict mode is recommended.

Use cases

Const

const fooSchema = {
  const: "foo",
} as const;

type Foo = FromSchema<typeof fooSchema>;
// => "foo"

Enums

const enumSchema = {
  enum: [true, 42, { foo: "bar" }],
} as const;

type Enum = FromSchema<typeof enumSchema>;
// => true | 42 | { foo: "bar"}

You can also go full circle with typescript enums.

enum Food {
  Pizza = "pizza",
  Taco = "taco",
  Fries = "fries",
}

const enumSchema = {
  enum: Object.values(Food),
} as const;

type Enum = FromSchema<typeof enumSchema>;
// => Food

Primitive types

const primitiveTypeSchema = {
  type: "null", // "boolean", "string", "integer", "number"
} as const;

type PrimitiveType = FromSchema<typeof primitiveTypeSchema>;
// => null, boolean, string or number
const primitiveTypesSchema = {
  type: ["null", "string"],
} as const;

type PrimitiveTypes = FromSchema<typeof primitiveTypesSchema>;
// => null | string

For more complex types, refinment keywords like required or additionalItems will apply πŸ™Œ

Arrays

const arraySchema = {
  type: "array",
  items: { type: "string" },
} as const;

type Array = FromSchema<typeof arraySchema>;
// => string[]

Tuples

const tupleSchema = {
  type: "array",
  items: [{ type: "boolean" }, { type: "string" }],
} as const;

type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string] | [boolean, string, ...unknown[]]

FromSchema supports the additionalItems keyword:

const tupleSchema = {
  type: "array",
  items: [{ type: "boolean" }, { type: "string" }],
  additionalItems: false,
} as const;

type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string]
const tupleSchema = {
  type: "array",
  items: [{ type: "boolean" }, { type: "string" }],
  additionalItems: { type: "number" },
} as const;

type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [boolean] | [boolean, string] | [boolean, string, ...number[]]

...as well as the minItems and maxItems keywords:

const tupleSchema = {
  type: "array",
  items: [{ type: "boolean" }, { type: "string" }],
  minItems: 1,
  maxItems: 2,
} as const;

type Tuple = FromSchema<typeof tupleSchema>;
// => [boolean] | [boolean, string]

Additional items will only work if Typescript's strictNullChecks option is activated

Objects

const objectSchema = {
  type: "object",
  properties: {
    foo: { type: "string" },
    bar: { type: "number" },
  },
  required: ["foo"],
} as const;

type Object = FromSchema<typeof objectSchema>;
// => { [x: string]: unknown; foo: string; bar?: number; }

FromSchema partially supports the additionalProperties and patternProperties keywords:

  • additionalProperties can be used to deny additional properties.
const closedObjectSchema = {
  ...objectSchema,
  additionalProperties: false,
} as const;

type Object = FromSchema<typeof closedObjectSchema>;
// => { foo: string; bar?: number; }
  • Used on their own, additionalProperties and/or patternProperties can be used to type unnamed properties.
const openObjectSchema = {
  type: "object",
  additionalProperties: {
    type: "boolean",
  },
  patternProperties: {
    "^S": { type: "string" },
    "^I": { type: "integer" },
  },
} as const;

type Object = FromSchema<typeof openObjectSchema>;
// => { [x: string]: string | number | boolean }
  • However, when used in combination with the properties keyword, extra properties will always be typed as unknown to avoid conflicts.

Combining schemas

AnyOf

const anyOfSchema = {
  anyOf: [
    { type: "string" },
    {
      type: "array",
      items: { type: "string" },
    },
  ],
} as const;

type AnyOf = FromSchema<typeof anyOfSchema>;
// => string | string[]

FromSchema will correctly infer factored schemas:

const factoredSchema = {
  type: "object",
  properties: {
    bool: { type: "boolean" },
  },
  required: ["bool"],
  anyOf: [
    {
      properties: {
        str: { type: "string" },
      },
      required: ["str"],
    },
    {
      properties: {
        num: { type: "number" },
      },
    },
  ],
} as const;

type Factored = FromSchema<typeof factoredSchema>;
// => {
//  [x:string]: unknown;
//  bool: boolean;
//  str: string;
// } | {
//  [x:string]: unknown;
//  bool: boolean;
//  num?: number;
// }

OneOf

For the moment, FromSchema will use the oneOf keyword in the same way as anyOf:

const catSchema = {
  type: "object",
  oneOf: [
    {
      properties: {
        name: { type: "string" },
      },
      required: ["name"],
    },
    {
      properties: {
        color: { enum: ["black", "brown", "white"] },
      },
    },
  ],
} as const;

type Cat = FromSchema<typeof catSchema>;
// => {
//  [x: string]: unknown;
//  name: string;
// } | {
//  [x: string]: unknown;
//  color?: "black" | "brown" | "white";
// }

// => Error will NOT be raised 😱
const invalidCat: Cat = { name: "Garfield" };

This may be revised soon now that not exclusions are now possible

AllOf

const addressSchema = {
  type: "object",
  allOf: [
    {
      properties: {
        address: { type: "string" },
        city: { type: "string" },
        state: { type: "string" },
      },
      required: ["address", "city", "state"],
    },
    {
      properties: {
        type: { enum: ["residential", "business"] },
      },
    },
  ],
} as const;

type Address = FromSchema<typeof addressSchema>;
// => {
//   [x: string]: unknown;
//   address: string;
//   city: string;
//   state: string;
//   type?: "residential" | "business";
// }

Not

const tupleSchema = {
  type: "array",
  items: [{ const: 1 }, { const: 2 }],
  additionalItems: false,
  not: {
    const: [1],
  },
} as const;

type Tuple = FromSchema<typeof tupleSchema>;
// => [] | [1, 2]
const primitiveTypeSchema = {
  not: {
    type: ["array", "object"],
  },
} as const;

type PrimitiveType = FromSchema<typeof primitiveTypeSchema>;
// => null | boolean | number | string

In objects and tuples, the exclusion will propagate to properties/items if it can collapse on a single one.

// πŸ‘ Can be propagated on "animal" property
const petSchema = {
  type: "object",
  properties: {
    animal: { enum: ["cat", "dog", "boat"] },
  },
  not: {
    properties: { animal: { const: "boat" } },
  },
  required: ["animal"],
  additionalProperties: false,
} as const;

type Pet = FromSchema<typeof petSchema>;
// => { animal: "cat" | "dog" }
// ❌ Cannot be propagated
const petSchema = {
  type: "object",
  properties: {
    animal: { enum: ["cat", "dog"] },
    color: { enum: ["black", "brown", "white"] },
  },
  not: {
    const: { animal: "cat", color: "white" },
  },
  required: ["animal", "color"],
  additionalProperties: false,
} as const;

type Pet = FromSchema<typeof petSchema>;
// => { animal: "cat" | "dog", color: "black" | "brown" | "white" }

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>;
// => should and will resolve to "number"

const incorrectSchema = {
  type: "number",
  not: { bogus: "option" },
} as const;

type Incorrect = FromSchema<typeof incorrectSchema>;
// => should resolve to "never" but will still resolve to "number"

Also, keep in mind that TypeScript misses refinment types:

const goodLanguageSchema = {
  type: "string",
  not: {
    enum: ["Bummer", "Silly", "Lazy sod !"],
  },
} as const;

type GoodLanguage = FromSchema<typeof goodLanguageSchema>;
// => string

If/Then/Else

const petSchema = {
  type: "object",
  properties: {
    animal: { enum: ["cat", "dog"] },
    dogBreed: { enum: Object.values(DogBreed) },
    catBreed: { enum: Object.values(CatBreed) },
  },
  required: ["animal"],
  additionalProperties: false,
  if: {
    properties: {
      animal: { const: "dog" },
    },
  },
  then: {
    required: ["dogBreed"],
    not: { required: ["catBreed"] },
  },
  else: {
    required: ["catBreed"],
    not: { required: ["dogBreed"] },
  },
} as const;

type Pet = FromSchema<typeof petSchema>;
// => { animal: "dog"; dogBreed: DogBreed }
// | { animal: "cat"; catBreed: CatBreed }

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.

Definitions

Since the introduction of template literal types with Typescript 4.1, the definitions keyword seems implementable in json-schema-to-ts.

I'll soon be looking into it. Meanwhile, feel free to open an issue πŸ€—

Frequently Asked Questions

Does json-schema-to-ts work on .json file schemas ?

Sadly, no 😭

FromSchema is based on type computations. By design, it only works on "good enough" material, i.e. narrow types ({ type: "string" }) and NOT widened ones ({ type: string } which can also represent { type: "number" }). However, JSON imports are widened by default. This is native TS behavior, there's no changing that.

If you really want use .json files, you can start by upvoting this feature request to implement .json imports as const on the official repo πŸ™‚ AND you can always cast imported schemas as their narrow types:

// dog.json
{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" },
    "hobbies": { "type": "array", "items": { "type": "string" } },
    "favoriteFood": { "enum": ["pizza", "taco", "fries"] }
  },
  "required": ["name", "age"]
}
import { FromSchema } from "json-schema-to-ts";

import dogRawSchema from "./dog.json";

const dogSchema = dogRawSchema as {
  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 = FromSchema<typeof dogSchema>;
// => Will work πŸ™Œ

It is technically code duplication, BUT TS will throw an errow if the narrow and widened types don't sufficiently overlap, which allows for partial type safety (roughly, everything but the object "leafs"). In particular, this will work well on object properties names, as object keys are not widened by default.

import { FromSchema } from "json-schema-to-ts";

import dogRawSchema from "./dog.json";

const dogSchema = dogoRawSchema as {
  type: "object";
  properties: {
    name: { type: "number" }; // "number" instead of "string" will go undetected...
    years: { type: "integer" }; // ...but "years" instead of "age" will not πŸ™Œ
    hobbies: { type: "array"; items: { type: "string" } };
    favoriteFood: { const: "pizza" }; // ..."const" instead of "enum" as well πŸ™Œ
  };
  required: ["name", "age"];
};

Can I assign JSONSchema to my schema and use FromSchema at the same time ?

json-schema-to-ts exports a JSONSchema type to help you write schemas:

import { FromSchema, JSONSchema } from "json-schema-to-ts";

const dogSchema: JSONSchema = { ... } as const;

type Dog = FromSchema<typeof dogSchema>;

For the same reason, this example will not work πŸ™…β€β™‚οΈ

FromSchema is based on type computations. By design, it only works on "good enough" material, i.e. narrow types ({ type: "string" }) and NOT widened ones ({ type: string } which can also represent { type: "number" }). For the compiler, assigning JSONSchema to your schema "blurs" its type to pretty much the widest possible schema type πŸ˜… That's why in this example, Dog will be equal to the never type.

So there is a sort of Heiseinberg's uncertainty principle at play here: You can either use FromSchema or JSONSchema, but not both at the same time.

The correct way to use them is the following:

  • Define a schema with the as const statement
  • Assign the JSONSchema type to it (allowing autocompletion and precise error highlighting)
  • Write the schema
  • Remove the type assignment
  • Use FromSchema πŸ™Œ

Will json-schema-to-ts impact the performances of my IDE/compiler ?

Long story short: no.

In your IDE, as long as you don't define all your schemas in the same file (which you shouldn't do anyway), file opening and type infering is still fast enough for you not to hardly notice anything, even on large schemas (200+ lines).

The same holds true for compilation. As far as I know (please, feel free to open an issue if you find otherwise), json-schema-to-ts has little to no impact on the TS compilation time.

I get a type instantiation is excessively deep and potentially infinite error, what should I do ?

Since Typescript 4.0 (which was unfortunately released after json-schema-to-ts πŸ˜…), the TS compiler raises this error when detecting long type computations, and potential infinite loops.

FromSchema goes through some pretty wild type recursions, so this is can be an issue on large schemas, particularly when using intersections (allOf) and exclusions (not, else).

I am working on simplifying the type computations. But for the moment, I don't have any better solution to give you other than ignoring the error with a @ts-ignore comment. This should not block the type computation, so the inferred type should still be valid.

If you find that it's not the case, please, feel free to open an issue.

About

Infer TS types from JSON schemas πŸ“

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 98.3%
  • Shell 1.4%
  • JavaScript 0.3%