MCPcopy
hub / github.com/ThomasAribart/json-schema-to-ts

github.com/ThomasAribart/json-schema-to-ts @v3.1.1 sqlite

repository ↗ · DeepWiki ↗ · release v3.1.1 ↗
20 symbols 146 edges 99 files 2 documented · 10%
README

💖 Huge thanks to the sponsors who help me maintain this repo:

Theodo TheodoPlus sign Your Brand Here

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.

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 JSONSchema

type 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:

const dogSchema = /** @type {const} @satisfies {import('json-schema-to-ts').JSONSchema} */ ({
  // Type-checked and autocompleted 🙌
  type: "object"
  ...
})

/** @type {import('json-schema-to-ts').FromSchema<typeof dogSchema>} */
const dog = { ... }

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
  • 🤝 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:
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 4.3+. Using strict mode is required, as well as (apparently) turning off noStrictGenericChecks.

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 🙌

Nullable

const nullableSchema = {
  type: "string",
  nullable: true,
} as const;

type Nullable = FromSchema<typeof nullableSchema>;
// => string | null

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

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:

const defaultedProp = {
  type: "object",
  properties: {
    foo: { type: "string", default: "bar" },
  },
  additionalProperties: false,
} as const;

type Object = FromSchema<typeof defaultedProp>;
// => { foo: string; }

type Object = FromSchema<
  typeof defaultedProp,
  { keepDefaultedPropertiesOptional: true }
>;
// => { foo?: string; }

FromSchema partially supports the additionalProperties, patternProperties and unevaluatedProperties keywords:

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

type Object = FromSchema<typeof closedObjectSchema>;
// => { foo: string; bar?: number; }
const closedObjectSchema = {
  type: "object",
  allOf: [
    {
      properties: {
        foo: { type: "string" },
      },
      required: ["foo"],
    },
    {
      properties: {
        bar: { type: "number" },
      },
    },
  ],
  unevaluatedProperties: 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.
const mixedObjectSchema = {
  type: "object",
  properties: {
    foo: { enum: ["bar", "baz"] },
  },
  additionalProperties: { type: "string" },
} as const;

type Object = FromSchema<typeof mixedObjectSchema>;
// => { [x: string]: unknown; foo?: "bar" | "baz"; }
  • Due to its context-dependent nature, unevaluatedProperties does not type extra-properties when used on its own. Use additionalProperties instead.
const openObjectSchema = {
  type: "object",
  unevaluatedProperties: {
    type: "boolean",
  },
} as const;

type Object = FromSchema<typeof openObjectSchema>;
// => { [x: string]: unknown }

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

FromSchema will parse 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" };

AllOf

```typescript const addressSchema = { type: "object", allOf: [ { properties: { address: { type: "string" }, city: { type: "string" }, state: { type: "string" }, }, required: ["address", "city", "state"], }, { properties: { type: { e

Core symbols most depended-on inside this repo

asConst
called by 12
src/utils/asConst.ts
wrapCompilerAsTypeGuard
called by 2
src/utils/type-guards/compiler.ts
wrapValidatorAsTypeGuard
called by 2
src/utils/type-guards/validator.ts
wrapCompilerAsTypeGuard
called by 0
builds/deno/index.mjs
wrapValidatorAsTypeGuard
called by 0
builds/deno/index.mjs
asConst
called by 0
builds/deno/index.mjs
wrapCompilerAsTypeGuard
called by 0
builds/deno/index.js
wrapValidatorAsTypeGuard
called by 0
builds/deno/index.js

Shape

Function 15
Enum 5

Languages

TypeScript100%

Modules by API surface

builds/deno/index.mjs4 symbols
builds/deno/index.js4 symbols
src/utils/type-guards/validator.unit.test.ts2 symbols
src/utils/type-guards/compiler.unit.test.ts2 symbols
src/tests/readme/ifThenElse.type.test.ts2 symbols
src/utils/type-guards/validator.ts1 symbols
src/utils/type-guards/compiler.ts1 symbols
src/utils/asConst.type.test.ts1 symbols
src/utils/asConst.ts1 symbols
src/tests/readme/enum.type.test.ts1 symbols
src/parse-schema/enum.unit.test.ts1 symbols

Dependencies from manifests, versioned

@babel/cli7.17.6 · 1×
@babel/core7.17.5 · 1×
@babel/plugin-transform-runtime7.17.0 · 1×
@babel/preset-env7.16.11 · 1×
@babel/preset-typescript7.16.7 · 1×
@babel/runtime7.18.3 · 1×
@rollup/plugin-typescript8.3.2 · 1×
@types/jest27.4.0 · 1×
@types/node20.5.7 · 1×
@typescript-eslint/eslint-plugin6.13.2 · 1×
@typescript-eslint/parser6.13.2 · 1×

For agents

$ claude mcp add json-schema-to-ts \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact