### Install json-schema-to-ts Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Install the library as a development dependency using npm or yarn. Requires TypeScript 4.3+ and `strict` mode enabled. ```bash # npm npm install --save-dev json-schema-to-ts # yarn yarn add --dev json-schema-to-ts ``` -------------------------------- ### Example JSON Schema for Dog Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/documentation/FAQs/does-json-schema-to-ts-work-on-json-file-schemas.md This is an example of a JSON schema defining properties for a dog, including name, age, hobbies, and favorite food. ```json { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" }, "hobbies": { "type": "array", "items": { "type": "string" } }, "favoriteFood": { "enum": ["pizza", "taco", "fries"] } }, "required": ["name", "age"] } ``` -------------------------------- ### Generic Mocker Function (Problematic) Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/documentation/FAQs/applying-from-schema-on-generics.md This example demonstrates a generic mocker function that initially leads to a TypeScript error when `FromSchema` is applied directly within the generic constraint. ```typescript import type { FromSchema, JSONSchema } from "json-schema-to-ts"; type Mocker = (schema: SCHEMA) => FromSchema; const getMockedData: Mocker = schema => { ... // logic here }; const dogSchema = { type: "object", ... // schema here } as const; const dogMock = getMockedData(dogSchema); ``` -------------------------------- ### Define JSON Schema and TypeScript Type Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Example of defining a JSON schema and its corresponding TypeScript type manually. This demonstrates the duplication that json-schema-to-ts aims to solve. ```typescript 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"; }; ``` -------------------------------- ### Wrap Compiler as Type Guard Factory with Ajv Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Use `wrapCompilerAsTypeGuard` to create a factory that returns a validator function. This validator narrows the data type based on the schema, offering performance benefits by pre-compiling schemas. This example uses Ajv. ```typescript import Ajv from "ajv"; import { wrapCompilerAsTypeGuard, $Compiler, FromSchema } from "json-schema-to-ts"; const ajv = new Ajv(); const $compile: $Compiler = schema => ajv.compile(schema); const compile = wrapCompilerAsTypeGuard($compile); const petSchema = { type: "object", properties: { name: { type: "string" }, age: { type: "number" }, }, required: ["name", "age"], additionalProperties: false, } as const; const isPet = compile(petSchema); // compiled once, reused many times const data: unknown = { name: "Dogo", age: 13 }; if (isPet(data)) { // data is typed as { name: string; age: number } console.log(data.age.toFixed(0)); // "13" — fully typed } console.log(isPet({ name: 42, age: "old" })); // false // With compile-time and validation-time options type CompileOpts = [{ cache: boolean }]; type ValidateOpts = [{ strict: boolean }]; const $compileOpts: $Compiler = (schema, { cache }) => { const validator = ajv.compile(schema); return (data, { strict }) => { const valid = validator(data); if (!valid && strict) throw new Error("Invalid"); return valid; }; }; const compileOpts = wrapCompilerAsTypeGuard($compileOpts); const isPetStrict = compileOpts(petSchema, { cache: true }); isPetStrict(data, { strict: true }); // throws or narrows ``` -------------------------------- ### Wrap Validator as Type Guard with Ajv Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Use `wrapValidatorAsTypeGuard` to enhance a validator function, making its `true` return value narrow the data type based on the schema. This example demonstrates its use with Ajv. ```typescript import Ajv from "ajv"; import { wrapValidatorAsTypeGuard, $Validator, FromSchema } from "json-schema-to-ts"; const ajv = new Ajv(); const $validate: $Validator = (schema, data) => ajv.validate(schema, data); const validate = wrapValidatorAsTypeGuard($validate); const petSchema = { type: "object", properties: { name: { type: "string" }, age: { type: "number" }, }, required: ["name", "age"], additionalProperties: false, } as const; type Pet = FromSchema; const data: unknown = { name: "Dogo", age: 13 }; if (validate(petSchema, data)) { // data is now typed as Pet inside this block console.log(data.name); // "Dogo" — fully typed } // With custom validation options type ValidationOptions = [{ shouldThrow: boolean }]; const $validateStrict: $Validator = (schema, data, opts) => { const isValid = ajv.validate(schema, data); if (!isValid && opts.shouldThrow) throw new Error("Validation failed"); return isValid; }; const validateStrict = wrapValidatorAsTypeGuard($validateStrict); validateStrict(petSchema, data, { shouldThrow: true }); // throws or narrows ``` -------------------------------- ### TypeScript AnyOf Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Demonstrates the use of `anyOf` to create types that can match one of several schemas. Supports factored schemas where common properties are correctly inferred. ```typescript const anyOfSchema = { anyOf: [ { type: "string" }, { type: "array", items: { type: "string" }, }, ], } as const; type AnyOf = FromSchema; // => string | string[] ``` ```typescript 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; // => { // [x:string]: unknown; // bool: boolean; // str: string; // } | { // [x:string]: unknown; // bool: boolean; // num?: number; // } ``` -------------------------------- ### Handle Schema References with `references` Option Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Use the `references` option to provide external schemas that can be resolved via `$ref`. This is essential for composing schemas that depend on other independently defined schemas, especially when they have `$id` properties. ```typescript const userSchema = { $id: "http://example.com/schemas/user.json", type: "object", properties: { name: { type: "string" }, age: { type: "integer" }, }, required: ["name", "age"], additionalProperties: false, } as const; const usersSchema = { type: "array", items: { $ref: "http://example.com/schemas/user.json", }, } as const; type Users = FromSchema< typeof usersSchema, { references: [typeof userSchema] } >; // => { // name: string; // age: string; // }[] const anotherUsersSchema = { $id: "http://example.com/schemas/users.json", type: "array", items: { $ref: "user.json" }, } as const; // => Will work as well 🙌 ``` -------------------------------- ### Using asConst for Runtime Schema Narrowing Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt The `asConst` utility function provides a runtime equivalent to the `as const` assertion for JSON schemas. It can be used in contexts where type assertions are not permitted and has no runtime overhead. ```typescript import { asConst, FromSchema } from "json-schema-to-ts"; const dogSchema = asConst({ type: "object", properties: { name: { type: "string" }, age: { type: "integer" }, }, required: ["name", "age"], additionalProperties: false, }); type Dog = FromSchema; // => { name: string; age: number } ``` ```typescript // Also usable with TS 4.9+ `satisfies` for type-checking + autocompletion import type { JSONSchema } from "json-schema-to-ts"; const checkedSchema = { type: "object", properties: { name: { type: "string" } }, required: ["name"], } as const satisfies JSONSchema; type Checked = FromSchema; // => { [x: string]: unknown; name: string } ``` -------------------------------- ### Handle `if/then/else` for Conditional Types Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Enable conditional parsing with `{ parseIfThenElseKeywords: true }`. This creates discriminated unions based on schema conditions. ```typescript import { FromSchema } from "json-schema-to-ts"; enum DogBreed { poodle = "poodle" } enum CatBreed { persan = "persan" } 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; // => { animal: "dog"; dogBreed: DogBreed; catBreed?: CatBreed } // | { animal: "cat"; catBreed: CatBreed; dogBreed?: DogBreed } ``` -------------------------------- ### Handle JSON Schema Combining Keywords: anyOf, allOf, oneOf Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Use `anyOf` and `oneOf` for union types, and `allOf` for intersection types that merge properties. Factored schemas are also supported. ```typescript import { FromSchema } from "json-schema-to-ts"; // anyOf — union type const stringOrArraySchema = { anyOf: [ { type: "string" }, { type: "array", items: { type: "string" } }, ], } as const; type StringOrArray = FromSchema; // => string | string[] ``` ```typescript // allOf — merged intersection const addressSchema = { type: "object", allOf: [ { properties: { street: { type: "string" }, city: { type: "string" } }, required: ["street", "city"], }, { properties: { type: { enum: ["residential", "business"] } }, }, ], } as const; type Address = FromSchema; // => { [x: string]: unknown; street: string; city: string; type?: "residential" | "business" } ``` ```typescript // Factored anyOf — shared properties distributed across branches 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; // => { [x: string]: unknown; bool: boolean; str: string } // | { [x: string]: unknown; bool: boolean; num?: number } ``` -------------------------------- ### Using asConst Utility for Schema Definition Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md An alternative to `as const` for defining schemas, the `asConst` utility narrows the schema's inferred type without impacting the compiled JavaScript code. ```typescript import { asConst } from "json-schema-to-ts"; const dogSchema = asConst({ type: "object", ... }); type Dog = FromSchema; ``` -------------------------------- ### Using JSDoc for Schema Type-Checking and Inference Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Illustrates how to use JSDoc comments with `@type` and `@satisfies` to achieve type-checking and autocompletion for JSON schemas, similar to the `satisfies` operator. ```typescript const dogSchema = /** @type {const} @satisfies {import('json-schema-to-ts').JSONSchema} */ ({ // Type-checked and autocompleted 🙌 type: "object" ... }) /** @type {import('json-schema-to-ts').FromSchema} */ const dog = { ... } ``` -------------------------------- ### Generic Mocker Function (Solution) Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/documentation/FAQs/applying-from-schema-on-generics.md This is the corrected version of the generic mocker function. By adding a second generic parameter `DATA` with a default value of `FromSchema`, the excessively deep type instantiation error is resolved. ```typescript import { FromSchema, JSONSchema } from "json-schema-to-ts"; type Mocker = >( schema: SCHEMA, ) => DATA; const getMockedData: Mocker = schema => { ... // logic here }; const dogSchema = { type: "object", ... // schema here } as const; // 🙌 Will work! const dogMock = getMockedData(dogSchema); ``` -------------------------------- ### Implement Custom Typeguard with FromSchema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Use FromSchema to create a custom typeguard. Ensure the validator is explicitly typed as Validator and FromSchema is used as the default value for the second generic. ```typescript 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 first const validate: Validator = >( schema: S, data: unknown ): data is T => { const isDataValid: boolean = ... // Implement validation here return isDataValid; }; const petSchema = { ... } as const let data: unknown; if (validate(petSchema, data)) { const { name, ... } = data; // data is typed as Pet 🙌 } ``` ```typescript type FromSchemaOptions = { parseNotKeyword: true }; type ValidationOptions = [{ fastValidate: boolean }] const validate: Validator = < S extends JSONSchema, T = FromSchema >( schema: S, data: unknown, ...validationOptions: ValidationOptions ): data is T => { ... }; ``` -------------------------------- ### Illustrating Type Safety with Schema Mismatches Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/documentation/FAQs/does-json-schema-to-ts-work-on-json-file-schemas.md Demonstrates how TypeScript can catch certain schema mismatches when casting imported JSON schemas to narrow types. Errors occur for incorrect property names or enum/const mismatches. ```typescript 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בול"]; }; ``` -------------------------------- ### Infer TypeScript Type from Nested JSON Schemas Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Demonstrates inferring types from nested or combined JSON schemas using `FromSchema`. The `as const` statement is crucial for proper type narrowing. ```typescript const catSchema = { ... } as const; const petSchema = { anyOf: [dogSchema, catSchema], } as const; type Pet = FromSchema; ``` -------------------------------- ### Handle `not` Keyword for Exclusion Types Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Enable exclusion parsing with `{ parseNotKeyword: true }`. This can narrow types by excluding specific values or properties. ```typescript import { FromSchema } from "json-schema-to-ts"; // Exclude specific values from a union const notArrayOrObjectSchema = { not: { type: ["array", "object"] }, } as const; type Primitive = FromSchema; // => null | boolean | number | string ``` ```typescript // Propagate exclusion to a single 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; // => { animal: "cat" | "dog" } ``` -------------------------------- ### Parse If/Then/Else Keywords in TypeScript Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Enable conditional logic parsing in JSON schemas using the `parseIfThenElseKeywords` option. This is useful for creating more complex and dynamic type definitions based on schema conditions. ```typescript const petSchema = { type: "object", properties: { animal: { enum: ["cat", "dog"] }, dogBreed: { enum: Object.values(DogBreed) }, catBreed: { enum: Object.values(CatBreed) }, }, required: ["animal"], if: { properties: { animal: { const: "dog" }, }, }, then: { required: ["dogBreed"], not: { required: ["catBreed"] }, }, else: { required: ["catBreed"], not: { required: ["dogBreed"] }, }, additionalProperties: false, } as const; type Pet = FromSchema; // => { // animal: "dog"; // dogBreed: DogBreed; // catBreed?: CatBreed | undefined // } | { // animal: "cat"; // catBreed: CatBreed; // dogBreed?: DogBreed | undefined // } ``` -------------------------------- ### Use Definitions in JSON Schema for TypeScript Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Leverage the `definitions` keyword in JSON Schema to define reusable sub-schemas, which can then be referenced within the main schema using `$ref`. This promotes modularity and reduces redundancy. ```typescript const userSchema = { type: "object", properties: { name: { $ref: "#/definitions/name" }, age: { $ref: "#/definitions/age" }, }, required: ["name", "age"], additionalProperties: false, definitions: { name: { type: "string" }, age: { type: "integer" }, }, } as const; type User = FromSchema; // => { // name: string; // age: number; // } ``` -------------------------------- ### Map Schema Patterns to Richer Output Types with `deserialize` Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt The `deserialize` option allows mapping schema patterns to richer TypeScript types, ideal for converting strings with specific formats (like `date-time` or `email`) to domain-specific types. ```typescript import { FromSchema } from "json-schema-to-ts"; type Email = string & { brand: "email" }; const userSchema = { type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email" }, birthDate: { type: "string", format: "date-time" }, }, required: ["name", "email", "birthDate"], additionalProperties: false, } as const; type User = FromSchema< typeof userSchema, { deserialize: [ { pattern: { type: "string"; format: "email" }; output: Email }, { pattern: { type: "string"; format: "date-time" }; output: Date }, ]; } >; // => { name: string; email: Email; birthDate: Date } ``` -------------------------------- ### TypeScript Tuple Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Defines a tuple schema with specific item types. Supports `additionalItems` for further configuration. ```typescript const tupleSchema = { type: "array", items: [{ type: "boolean" }, { type: "string" }], } as const; type Tuple = FromSchema; // => [] | [boolean] | [boolean, string] | [boolean, string, ...unknown[]] ``` ```typescript const tupleSchema = { type: "array", items: [{ type: "boolean" }, { type: "string" }], additionalItems: false, } as const; type Tuple = FromSchema; // => [] | [boolean] | [boolean, string] ``` ```typescript const tupleSchema = { type: "array", items: [{ type: "boolean" }, { type: "string" }], additionalItems: { type: "number" }, } as const; type Tuple = FromSchema; // => [] | [boolean] | [boolean, string] | [boolean, string, ...number[]] ``` ```typescript const tupleSchema = { type: "array", items: [{ type: "boolean" }, { type: "string" }], minItems: 1, maxItems: 2, } as const; type Tuple = FromSchema; // => [boolean] | [boolean, string] ``` -------------------------------- ### Generic Function with FromSchema Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt When creating generic utilities with `json-schema-to-ts`, use a two-generic pattern (`SCHEMA` and a defaulted `DATA`) to prevent TypeScript's 'type instantiation is excessively deep' error. This ensures `FromSchema` is not directly used as a constraint. ```typescript import type { FromSchema, JSONSchema } from "json-schema-to-ts"; // ✅ Correct — DATA defaults to FromSchema type Mocker = >( schema: SCHEMA, ) => DATA; const getMockedData: Mocker = schema => { // runtime mock logic here return {} as any; }; const dogSchema = { type: "object", properties: { name: { type: "string" }, age: { type: "integer" } }, required: ["name", "age"], additionalProperties: false, } as const; const mock = getMockedData(dogSchema); // mock is typed as { name: string; age: number } ✅ // ❌ Incorrect — causes "type instantiation is excessively deep" error // type Mocker = (schema: SCHEMA) => FromSchema; ``` -------------------------------- ### Parse AllOf keyword in TypeScript Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Combines multiple schemas using the 'allOf' keyword. Ensures that the resulting type includes properties and constraints from all specified subschemas. ```typescript 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; // => { // [x: string]: unknown; // address: string; // city: string; // state: string; // type?: "residential" | "business"; // } ``` -------------------------------- ### TypeScript Object Schema with Additional Properties Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Illustrates how `additionalProperties` and `unevaluatedProperties` can be used to define behavior for properties not explicitly listed. Setting them to `false` denies additional properties. ```typescript const closedObjectSchema = { ...objectSchema, additionalProperties: false, } as const; type Object = FromSchema; // => { foo: string; bar?: number; } ``` ```typescript const closedObjectSchema = { type: "object", allOf: [ { properties: { foo: { type: "string" }, }, required: ["foo"], }, { properties: { bar: { type: "number" }, }, }, ], unevaluatedProperties: false, } as const; type Object = FromSchema; // => { foo: string; bar?: number; } ``` ```typescript const openObjectSchema = { type: "object", additionalProperties: { type: "boolean", }, patternProperties: { "^S": { type: "string" }, "^I": { type: "integer" }, }, } as const; type Object = FromSchema; // => { [x: string]: string | number | boolean } ``` ```typescript const mixedObjectSchema = { type: "object", properties: { foo: { enum: ["bar", "baz"] }, }, additionalProperties: { type: "string" }, } as const; type Object = FromSchema; // => { [x: string]: unknown; foo?: "bar" | "baz"; } ``` ```typescript const openObjectSchema = { type: "object", unevaluatedProperties: { type: "boolean", }, } as const; type Object = FromSchema; // => { [x: string]: unknown } ``` -------------------------------- ### Specify Deserialization Patterns with `deserialize` Option Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Configure custom deserialization logic for specific schema formats using the `deserialize` option. This allows mapping string representations of data (like email or date-time) to their corresponding TypeScript types (e.g., `Email` or `Date`). ```typescript const userSchema = { type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email", }, birthDate: { type: "string", format: "date-time", }, }, required: ["name", "email", "birthDate"], additionalProperties: false, } as const; type Email = string & { brand: "email" }; type User = FromSchema< typeof userSchema, { deserialize: [ { pattern: { type: "string"; format: "email"; }; output: Email; }, { pattern: { type: "string"; format: "date-time"; }; output: Date; }, ]; } >; // => { // name: string; // email: Email; // birthDate: Date; // } ``` -------------------------------- ### Generate TypeScript Type from Invalid JSON Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Demonstrates how `FromSchema` can identify an invalid schema at compile time, resulting in a `never` type. This highlights the schema validation capabilities of the library. ```typescript 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; type Address = FromSchema; // => never 🙌 ``` -------------------------------- ### Resolve External $ref with `references` Option Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Use the `references` option to hydrate external schemas identified by `$id` at the type level. Relative `$id` resolution is supported. ```typescript import { FromSchema } from "json-schema-to-ts"; // Internal definitions/$ref const userSchema = { type: "object", properties: { name: { $ref: "#/definitions/name" }, age: { $ref: "#/definitions/age" }, }, required: ["name", "age"], additionalProperties: false, definitions: { name: { type: "string" }, age: { type: "integer" }, }, } as const; type User = FromSchema; // => { name: string; age: number } // External $ref resolved via `references` option const personSchema = { $id: "http://example.com/schemas/person.json", type: "object", properties: { name: { type: "string" }, age: { type: "integer" }, }, required: ["name", "age"], additionalProperties: false, } as const; const teamSchema = { type: "array", items: { $ref: "http://example.com/schemas/person.json" }, } as const; type Team = FromSchema; // => { name: string; age: number }[] ``` -------------------------------- ### TypeScript Object Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Defines an object schema with properties and required fields. `FromSchema` infers types including optional and defaulted properties. ```typescript const objectSchema = { type: "object", properties: { foo: { type: "string" }, bar: { type: "number" }, }, required: ["foo"], } as const; type Object = FromSchema; // => { [x: string]: unknown; foo: string; bar?: number; } ``` -------------------------------- ### Extend JSON Schema with Custom Properties Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Utilize `ExtendedJSONSchema` and `FromExtendedSchema` to incorporate custom properties into your JSON schemas. This allows for schema extensions beyond the standard JSON Schema specification, enabling more specialized type generation. ```typescript 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; type BigInt = FromExtendedSchema< CustomProps, typeof bigIntSchema, { // 👇 Works very well with the deserialize option! deserialize: [ { pattern: { type: "number"; numberType: "bigInt"; }; output: bigint; }, ]; } >; ``` -------------------------------- ### TypeScript Object Schema with Defaulted Properties Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Demonstrates handling of defaulted properties in object schemas. The `keepDefaultedPropertiesOptional` option can control whether defaulted properties remain optional. ```typescript const defaultedProp = { type: "object", properties: { foo: { type: "string", default: "bar" }, }, additionalProperties: false, } as const; type Object = FromSchema; // => { foo: string; } ``` ```typescript type Object = FromSchema< typeof defaultedProp, { keepDefaultedPropertiesOptional: true } >; // => { foo?: string; } ``` -------------------------------- ### Infer Types from Schemas with Custom Properties using `FromExtendedSchema` Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Use `ExtendedJSONSchema` and `FromExtendedSchema` to handle custom schema properties, enabling type inference for extended JSON Schema vocabularies like OpenAPI extensions. Combine with `deserialize` for custom type mapping. ```typescript import type { ExtendedJSONSchema, FromExtendedSchema } from "json-schema-to-ts"; type CustomProps = { numberType: "int" | "float" | "bigInt"; }; // Schema is validated to only allow known custom values const bigIntSchema = { type: "number", numberType: "bigInt", } as const satisfies ExtendedJSONSchema; type BigInt = FromExtendedSchema< CustomProps, typeof bigIntSchema, { deserialize: [ { pattern: { type: "number"; numberType: "bigInt" }; output: bigint; }, ]; } >; // => bigint // Nested extended properties work too const nestedSchema = { type: "object", properties: { value: { numberType: "bigInt" } }, required: ["value"], additionalProperties: false, } as const; type Nested = FromExtendedSchema< CustomProps, typeof nestedSchema, { deserialize: [{ pattern: { numberType: "bigInt" }; output: bigint }] } >; // => { value: bigint } ``` -------------------------------- ### Parse OneOf keyword in TypeScript Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Handles the 'oneOf' keyword similarly to 'anyOf'. Useful for defining schemas that can match one of several subschemas. ```typescript const catSchema = { type: "object", oneOf: [ { properties: { name: { type: "string" }, }, required: ["name"], }, { properties: { color: { enum: ["black", "brown", "white"] }, }, }, ], } as const; type Cat = FromSchema; // => { // [x: string]: unknown; // name: string; // } | { // [x: string]: unknown; // color?: "black" | "brown" | "white"; // } // => Error will NOT be raised 😱 const invalidCat: Cat = { name: "Garfield" }; ``` -------------------------------- ### Parse Not keyword with parseNotKeyword option Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Enables parsing of the 'not' keyword using the `parseNotKeyword: true` option. Be aware that exclusions might sometimes resolve to 'any' due to TypeScript limitations. ```typescript const tupleSchema = { type: "array", items: [{ const: 1 }, { const: 2 }], additionalItems: false, not: { const: [1], }, } as const; type Tuple = FromSchema; // => [] | [1, 2] ``` ```typescript const primitiveTypeSchema = { not: { type: ["array", "object"], }, } as const; type PrimitiveType = FromSchema< typeof primitiveTypeSchema, { parseNotKeyword: true } >; // => null | boolean | number | string ``` ```typescript // 👍 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; // => { animal: "cat" | "dog" } ``` ```typescript // ❌ 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; // => { animal: "cat" | "dog", color: "black" | "brown" | "white" } ``` ```typescript const oddNumberSchema = { type: "number", not: { multipleOf: 2 }, } as const; type OddNumber = FromSchema; // => should and will resolve to "number" const incorrectSchema = { type: "number", not: { bogus: "option" }, } as const; type Incorrect = FromSchema; // => should resolve to "never" but will still resolve to "number" ``` ```typescript const goodLanguageSchema = { type: "string", not: { enum: ["Bummer", "Silly", "Lazy sod !"], }, } as const; type GoodLanguage = FromSchema< typeof goodLanguageSchema, { parseNotKeyword: true } >; // => string ``` -------------------------------- ### Using satisfies Operator for Type-Checking Schemas Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Leverage TypeScript's `satisfies` operator (TS 4.9+) for compile-time type-checking and autocompletion of JSON schemas, combined with `FromSchema` for type inference. ```typescript import type { JSONSchema } from "json-schema-to-ts"; const dogSchema = { // Type-checked and autocompleted 🙌 type: "object" ... } as const satisfies JSONSchema type Dog = FromSchema ``` -------------------------------- ### Generate Type from Constant Value Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Creates a TypeScript type that strictly matches a constant string value defined in the schema. ```typescript const fooSchema = { const: "foo", } as const; type Foo = FromSchema; // => "foo" ``` -------------------------------- ### Inferring TypeScript Types from JSON Schemas with FromSchema Source: https://context7.com/thomasaribart/json-schema-to-ts/llms.txt Use `FromSchema` with a schema defined `as const` to automatically infer the corresponding TypeScript type. This works for various schema structures including objects, unions, constants, enums, and composed schemas. ```typescript import { FromSchema } from "json-schema-to-ts"; // Basic object schema 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"], additionalProperties: false, } as const; type Dog = FromSchema; // => { name: string; age: number; hobbies?: string[]; favoriteFood?: "pizza" | "taco" | "fries" } ``` ```typescript // Union of types const idSchema = { type: ["string", "number"] } as const; type Id = FromSchema; // => string | number ``` ```typescript // Constant value const statusSchema = { const: "active" } as const; type Status = FromSchema; // => "active" ``` ```typescript // Enum const roleSchema = { enum: ["admin", "user", 42] } as const; type Role = FromSchema; // => "admin" | "user" | 42 ``` ```typescript // Nested / composed schemas const catSchema = { type: "object", properties: { name: { type: "string" } }, required: ["name"], additionalProperties: false, } as const; const petSchema = { anyOf: [dogSchema, catSchema] } as const; type Pet = FromSchema; // => Dog | { name: string } ``` -------------------------------- ### Generate Type from Primitive JSON Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Defines a TypeScript type based on a single primitive type specified in the schema. Supports various primitive types like null, boolean, string, integer, and number. ```typescript const primitiveTypeSchema = { type: "null", // "boolean", "string", "integer", "number" } as const; type PrimitiveType = FromSchema; // => null, boolean, string or number ``` -------------------------------- ### Generate Type for Nullable String Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Defines a TypeScript type that can be either a string or null, based on the `nullable: true` property in the schema. ```typescript const nullableSchema = { type: "string", nullable: true, } as const; type Nullable = FromSchema; // => string | null ``` -------------------------------- ### Generate Type from Multiple Primitive Types Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Creates a union type in TypeScript by specifying an array of primitive types in the JSON schema. This allows for more flexible type definitions. ```typescript const primitiveTypesSchema = { type: ["null", "string"], } as const; type PrimitiveTypes = FromSchema; // => null | string ``` -------------------------------- ### Casting JSON Schema for Type Safety Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/documentation/FAQs/does-json-schema-to-ts-work-on-json-file-schemas.md Import a JSON schema and cast it to a narrow type to ensure compatibility with json-schema-to-ts. This approach provides partial type safety, especially for object property names. ```typescript 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; // => Will work 🙌 ``` -------------------------------- ### Generate Type for Array of Strings Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Infers a TypeScript array type where all elements are strings, based on the `items` property defining the type of array elements. ```typescript const arraySchema = { type: "array", items: { type: "string" }, } as const; type Array = FromSchema; // => string[] ``` -------------------------------- ### Generate Type from Enum Schema Source: https://github.com/thomasaribart/json-schema-to-ts/blob/main/README.md Infers a union type from an enum array in the JSON schema. This can also map to TypeScript enums. ```typescript const enumSchema = { enum: [true, 42, { foo: "bar" }], } as const; type Enum = FromSchema; // => true | 42 | { foo: "bar"} ``` ```typescript enum Food { Pizza = "pizza", Taco = "taco", Fries = "fries", } const enumSchema = { enum: Object.values(Food), } as const; type Enum = FromSchema; // => Food ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.