### Install TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/readme.md Install the TypeBox library using npm. ```bash $ npm install typebox ``` -------------------------------- ### Install Legacy TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/overview/1_install.md Use this command to install pre-1.0 versions of TypeBox. ```bash $ npm install @sinclair/typebox --save ``` -------------------------------- ### Install Latest TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/overview/1_install.md Use this command to install post-1.0 versions of TypeBox. ```bash $ npm install typebox --save ``` -------------------------------- ### Install TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/changelog/1.0.0.md Install TypeBox 1.0.0 using npm. For older versions (0.34.x), use the @sinclair/typebox package. ```bash $ npm install typebox --save # TypeBox 1.0.0 $ npm install @sinclair/typebox --save # TypeBox 0.34.x ``` -------------------------------- ### Install TypeBox 0.x (LTS) Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/overview/3_versions.md Use this command to install the Long Term Support (LTS) version of TypeBox, compatible with TypeScript 4-6. Supports both ESM and CJS. ```bash $ npm install @sinclair/typebox # 0.x - LTS | TS 4-6 ``` -------------------------------- ### Install TypeBox 1.x (Latest) Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/overview/3_versions.md Install the latest version of TypeBox, which requires TypeScript 7 native compiler. This version offers advanced type inference and JSON Schema 2020-12 compliance. Supports ESM only. ```bash $ npm install typebox # 1.x - Latest | TS 7 Native ``` -------------------------------- ### Optional Ajv Setup with TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/overview/2_setup.md Integrate TypeBox with Ajv for schema validation. This setup includes common Ajv formats and compiles a basic object schema. ```typescript import Type from 'typebox' import addFormats from 'ajv-formats' import Ajv from 'ajv' const ajv = addFormats(new Ajv({}), [ 'date-time', 'time', 'date', 'email', 'hostname', 'ipv4', 'ipv6', 'uri', 'uri-reference', 'uuid', 'uri-template', 'json-pointer', 'relative-json-pointer', 'regex' ]) // ... const check = ajv.compile(Type.Object({ x: Type.Number(), y: Type.Number(), z: Type.Number() })) const R = check({ x: 1, y: 2, z: 3 }) // const R = true ``` -------------------------------- ### TypeBox with Ajv Integration Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/overview/2_setup.html This example shows how to set up Ajv with TypeBox for runtime validation. It includes importing necessary libraries and compiling a schema. ```typescript import Type from 'typebox' import addFormats from 'ajv-formats' import Ajv from 'ajv' const ajv = addFormats(new Ajv({}), [ 'date-time', 'time', 'date', 'email', 'hostname', 'ipv4', 'ipv6', 'uri', 'uri-reference', 'uuid', 'uri-template', 'json-pointer', 'relative-json-pointer', 'regex' ]) // ... const check = ajv.compile(Type.Object({ x: Type.Number(), y: Type.Number(), z: Type.Number() })) const R = check({ x: 1, y: 2, z: 3 }) ``` -------------------------------- ### TypeBox Script Extension Types Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html Examples of using Type.Script for extension types like Capitalize, Uncapitalize, and Evaluate. ```typescript const T14 = Type.Script('Capitalize<"hello">') const T15 = Type.Script('Uncapitalize<"hello">') ``` ```typescript const T16 = Type.Script('Evaluate<{ x: number } & { y: number }>') const T17 = Type.Script('Options<{ x: number }, { additionalProperties: false }>') ``` -------------------------------- ### Wide Data Structure Example Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/5_scaling.html Demonstrates a wide data structure using Script, which supports many elements without increasing depth significantly. ```typescript const T = Type.Script(`[ // 1 x depth 0, 1, 2, 3, 4, 5, 6, 7, // 128 x elements 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, ]`) ``` -------------------------------- ### Decode with Custom Codec Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/decode.md Example of using Value.Decode with a custom Codec for timestamp conversion. Wrap in try-catch for error handling. ```typescript const Timestamp = Type.Codec(Type.Number()) .Decode(value => new Date(value)) .Encode(value => value.getTime()) const T = Type.Object({ date: Timestamp }) const R = Value.Decode(T, { date: 12345 }) // const R = { // date: 1970-01-01T00:00:12.345Z // } ``` -------------------------------- ### Define a Basic Interface Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/interface.html Use Type.Interface to create an object schema. This example defines an interface with a single number property 'a'. ```typescript const A = Type.Interface([], { a: Type.Number() }) ``` -------------------------------- ### Define Number and String Types with Constraints Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/overview.md Create a number type with minimum and maximum constraints, and a string type with an email format. These examples demonstrate passing options and constraints. ```typescript const T = Type.Number({ minimum: 0, maximum: 100 }) ``` ```typescript const S = Type.String({ format: 'email' }) ``` -------------------------------- ### Basic Value.Parse Usage Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/value/parse.html Demonstrates basic usage of Value.Parse to validate a string. An example of an invalid input that throws a ParseError is also shown. ```typescript const R = Value.Parse(Type.String(), 'hello') // const R: string = "hello" const E = Value.Parse(Type.String(), 12345) // throws ParseError ``` -------------------------------- ### Map and Rename Property Keys with Script Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/4_advanced.html Use Script to map and rename property keys in a schema. This example transforms 'x', 'y', 'z' to 'propX', 'propY', 'propZ'. ```typescript const T = Type.Object({ x: Type.Number(), y: Type.Number(), z: Type.Number() }) const S = Type.Script({ T }, '{ [K in keyof T as `prop${Uppercase}`]: T[K] }') // const S: TObject({ // propX: TNumber, // propY: TNumber, // propZ: TNumber; // }) ``` -------------------------------- ### Deeply Nested Structure Example Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/5_scaling.html Illustrates a deeply nested structure that will quickly exceed TypeScript's instantiation depth limits. ```typescript const T = Type.Script(`{ // depth + 1 a: { // depth + 2 b: { // depth + 3 c: { // depth + 4 d: { // instantiation too deep e: 1 } } } } }`) ``` -------------------------------- ### Indexed Access Lookup with Type.Index Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/indexed.md Use Type.Index to perform an indexed access lookup on a type. This example demonstrates selecting properties 'x' and 'y' from an object type. ```typescript const T = Type.Object({ x: Type.Literal(1), y: Type.Literal(2), z: Type.Literal(3) }) const S = Type.Index(T, Type.Union([ Type.Literal('x'), Type.Literal('y') ])) ``` -------------------------------- ### Define and Use a Value.Pipeline Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/pipeline.md This example demonstrates how to define a custom Parse pre-processing pipeline using the Pipeline utility. It includes operations for cloning, defaulting, converting, cleaning, and parsing values. A typed wrapper function `Parse` is provided for type inference. ```typescript import Value, { Pipeline } from 'typebox/value' import Type from 'typebox' // ------------------------------------------------------- // Pipeline: Definition // // The following is a custom Parse pre-processing pipeline // that runs a sequence of operations on a value before // attempting to Parse. These operations can be run in // any order. User defined pre-processing logic can // also be added as pipeline stages if necessary. // // ------------------------------------------------------- const ParsePipeline = Pipeline([ (_context, _type, value) => Value.Clone(value), (context, type, value) => Value.Default(context, type, value), (context, type, value) => Value.Convert(context, type, value), (context, type, value) => Value.Clean(context, type, value), (context, type, value) => Value.Parse(context, type, value) ]) // ------------------------------------------------------- // Pipeline: Inference // // Pipelines return type `unknown` as it is not possible to // determine the last operation of the pipeline returned a // correct value. As we know the Parse operation will assert // the value, we can wrap calls to pipeline in a function // which provides type type inference for the pipeline. // // ------------------------------------------------------- export function Parse(type: Type, value: unknown): Type.Static { return ParsePipeline(type, value) as never } // ------------------------------------------------------- // Usage // ------------------------------------------------------- const result = Parse(Type.String(), 1234) console.log(result) ``` -------------------------------- ### Compile and Parse TypeBox Schema Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/schema/overview.md Compiles a TypeBox object schema and then parses data against it. Ensure TypeBox is installed and imported correctly. ```typescript import Schema from 'typebox/schema' import { Type } from 'typebox' // ------------------------------------------------------------------------------- // Compile // ------------------------------------------------------------------------------- const User = Schema.Compile(Type.Object({ id: Type.String(), name: Type.String(), email: Type.String({ format: 'email' }) })) // ------------------------------------------------------------------------------- // Parse // ------------------------------------------------------------------------------- const user = User.Parse({ id: '65f1a2b3c4d5e6f7a8b9c0d1', name: 'user', email: 'user@domain.com' }) ``` -------------------------------- ### Implement Uint8Array Type with Type.Base Source: https://github.com/sinclairzx81/typebox/blob/main/changelog/1.0.0-migration.md Example of creating a custom Uint8Array type using Type.Base, including required Check, Errors, and Clone methods for validation and type composition. ```typescript import Type from 'typebox' export class TUint8Array extends Type.Base { // required: Used by validation public override Check(value: unknown): value is Uint8Array { return value instanceof Uint8Array } // required: Used by validation public override Errors(value: unknown): object[] { return !this.Check(value) ? [{ message: 'not a Uint8Array'}] : [] } // required: Used by type compositor public override Clone(): TUint8Array { return new TUint8Array() } } export function Uint8Array(): TUint8Array { return new TUint8Array() } ``` -------------------------------- ### Use the Typed Parse Function Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/value/pipeline.html Example of using the custom Parse function with a TypeBox schema. It demonstrates parsing a number into a string type. ```typescript // ------------------------------------------------------- // Usage // ------------------------------------------------------- const result = Parse(Type.String(), 1234) console.log(result) ``` -------------------------------- ### Map and Rename Object Keys with Script Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/4_advanced.md Use Script to map and rename property keys of an object schema. This example transforms keys 'x', 'y', 'z' to 'propX', 'propY', 'propZ'. ```typescript const T = Type.Object({ x: Type.Number(), y: Type.Number(), z: Type.Number() }) const S = Type.Script({ T }, '{ [K in keyof T as `prop${Uppercase}`]: T[K] }') ``` -------------------------------- ### Define and Decode Timestamp with TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/value/decode.html Example of defining a custom Timestamp type with Decode and Encode callbacks, then using Value.Decode to process a value. ```typescript const Timestamp = Type.Codec(Type.Number()) .Decode(value => new Date(value)) .Encode(value => value.getTime()) const T = Type.Object({ date: Timestamp }) const R = Value.Decode(T, { date: 12345 }) // const R = { // date: 1970-01-01T00:00:12.345Z // } ``` -------------------------------- ### Create JSON Schema from TypeScript Syntax Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/overview/overview.html Use the Type.Script function to create JSON Schema from TypeScript syntax. This example defines an object with three number properties and then creates a schema where these properties can also be null. ```typescript import Type from 'typebox' const T = Type.Script(`{ x: number y: number z: number }`) type T = Static const S = Type.Script({ T }, `{ [K in keyof T]: T[K] | null }`) type S = Type.Static ``` -------------------------------- ### Get Validation Errors with Value.Errors Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/value/errors.html Use Value.Errors to get an array of validation errors for a value. Call this only after a failed Check for performance. The example shows how to access invalid values using Value.Pointer.Get. ```typescript const T = Type.Object({ x: Type.Number(), y: Type.Number() }) const value = { x: 'not-a-number' } const errors = Value.Errors(T, value) // const errors = [{ // keyword: 'required', // schemaPath: '#/required', // instancePath: '', // params: { requiredProperties: [ 'y' ] }, // message: 'must have required properties y' // }, { // keyword: 'type', // schemaPath: '#/properties/x/type', // instancePath: '/x', // params: { type: 'number' }, // message: 'must be number' // }] // ------------------------------------------------------------------ // // Optional // // Use Value.Pointer.Get to access invalid values via `instancePath` // // ------------------------------------------------------------------ const errorsWithValue = errors.map(error => { return { ...error, value: Value.Pointer.Get(value, error.instancePath) } }) ``` -------------------------------- ### Create a TypeBox Array of Numbers Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/array.html Use Type.Array to create an array schema. Specify the type of items the array will contain as an argument. This example creates an array that only accepts numbers. ```typescript const T = Type.Array(Type.Number()) ``` -------------------------------- ### Get Validation Errors for a Value Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/errors.md Use `Value.Errors` to get an array of validation errors for a given value against a TypeBox schema. Call this only after a `Check` has failed. The example also demonstrates accessing the invalid value using `Value.Pointer.Get`. ```typescript const T = Type.Object({ x: Type.Number(), y: Type.Number() }) const value = { x: 'not-a-number' } const errors = Value.Errors(T, value) // const errors = [{ // keyword: 'required', // schemaPath: '#/required', // instancePath: '', // params: { requiredProperties: [ 'y' ] }, // message: 'must have required properties y' // }, { // keyword: 'type', // schemaPath: '#/properties/x/type', // instancePath: '/x', // params: { type: 'number' }, // message: 'must be number' // }] // ------------------------------------------------------------------ // // Optional // // Use Value.Pointer.Get to access invalid values via `instancePath` // // ------------------------------------------------------------------ const errorsWithValue = errors.map(error => { return { ...error, value: Value.Pointer.Get(value, error.instancePath) } }) ``` -------------------------------- ### Validate Schema and Get Errors Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/schema/4_errors.md Use Schema.Errors to validate an object against a schema. It returns a tuple where the first element is a boolean indicating success, and the second is an array of validation errors. This example shows validation of an object missing required properties and with an incorrect type for a property. ```typescript import Schema from 'typebox/schema' // ------------------------------------------------------------------ // Schema // ------------------------------------------------------------------ const T = { type: 'object', required: ['x', 'y', 'z'], properties: { x: { type: 'number' }, y: { type: 'number' }, z: { type: 'number' } } } as const // ------------------------------------------------------------------ // Errors // ------------------------------------------------------------------ // where E is: [success: boolean, errors: TLocalizedValidationError[]] const E = Schema.Errors(T, { x: null }) console.log(errors) ``` -------------------------------- ### Create a Rest Type with Type.Rest Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/rest.md Use Type.Rest to define a Rest type, which is an array of tuples. This example shows how to create a Rest type with specific tuple items and infer its static type. ```typescript const T = Type.Rest(Type.Tuple([ Type.Literal(1), Type.Literal(2) ])) type T = Static ``` -------------------------------- ### Type.String() - Creating a String Type Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/string.html This snippet demonstrates how to create a basic String type using Type.String() and its corresponding static type. ```APIDOC ## Type.String() ### Description Creates a String type. ### Method Type.String() ### Endpoint N/A (Client-side library function) ### Request Body N/A ### Request Example ```json { "example": "const T = Type.String()" } ``` ### Response #### Success Response (200) - **T** (object) - Represents the String type schema. ```json { "example": "{\n type: 'string'\n}" } ``` ### Static Type Example ```typescript import { Type, Static } from '@sinclair/typebox' const T = Type.String() type T = Static // type T = string ``` ``` -------------------------------- ### Create TypeBox Type with Experimental 'with' Keyword Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/2_options.md Demonstrates the experimental 'with' keyword syntax for inlining options directly within a TypeBox Script type definition. Use with caution due to potential future changes. ```typescript const VectorC = Type.Script(`{ x: number with { minimum: 0, maximum: 1 } y: number with { minimum: 0, maximum: 1 } } with { additionalProperties: false }`) ``` -------------------------------- ### Import System Module Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/system/overview.md Import necessary components from the TypeBox system module. Ensure these are available in your project. ```typescript import { Settings, Locale, Memory } from 'typebox/system' ``` -------------------------------- ### Get Validator Code Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/compile/1_validator.md Returns the generated JavaScript code for this validator. Assumes 'C' is a compiled Validator instance. ```typescript const R = C.Code() ``` -------------------------------- ### TypeBox and TypeScript Shared Type Definition Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/2_options.html Example of defining a `Vector` type using `Options` that can be shared between TypeBox and TypeScript. This demonstrates how to apply options like `minimum`, `maximum`, and `additionalProperties` to nested types. ```typescript type Vector = Options<{ x: Options y: Options, }, { additionalProperties: false }> ``` -------------------------------- ### Function Type Expressions Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html Shows how to define function types with parameters and return types using Type.Script. ```typescript const T22 = Type.Script(`(a: number, b: number) => number`) // TFunction<[TNumber, TNumber], TNumber> ``` -------------------------------- ### Create TypeBox Type with Script and Options Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/2_options.md Illustrates creating a TypeBox type by passing a string representation of the Options generic to Type.Script(). ```typescript const VectorB = Type.Script(`Options<{ x: Options, y: Options, }, { additionalProperties: false }>`) ``` -------------------------------- ### Format Registry API Change Source: https://github.com/sinclairzx81/typebox/blob/main/changelog/1.0.0-migration.md Demonstrates the change in accessing the FormatRegistry, moving from a global import to the Format submodule. ```typescript import { FormatRegistry } from '@sinclair/typebox' FormatRegistry.Set('foo', value => value === 'foo') ``` ```typescript import Format from 'typebox/format' Format.Set('foo', value => value === 'foo') ``` -------------------------------- ### Get Value with Json Pointer Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/value/pointer.html Retrieves a value from an object at the specified Json Pointer path. Returns undefined if the path does not exist. ```typescript const X = { x: 1 } const A = Value.Pointer.Get(X, '/x') // const A = 1 const B = Value.Pointer.Get(X, '/y') // const B = undefined ``` -------------------------------- ### Type.Number() - Creating a Number Type Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/number.html This snippet demonstrates how to create a basic Number type using TypeBox and how to infer its static type. ```APIDOC ## Type.Number() ### Description Creates a Number type. ### Method TypeBox Function ### Endpoint N/A ### Request Body N/A ### Request Example ```typescript const T = Type.Number() // const T = { // type: 'number' // } type T = Static // type T = number ``` ### Response N/A ``` -------------------------------- ### Unwrap Promise Type with Type.Awaited Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/awaited.html Use Type.Awaited to get the type of the value a Promise resolves to. Ensure the input is a Promise type. ```typescript const T = Type.Promise(Type.String()) const S = Type.Awaited(T) // const S: TString ``` -------------------------------- ### Get Value with Json Pointer Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/pointer.md Retrieves a value from an object at the specified Json Pointer path. Returns undefined if the path does not exist. ```typescript const X = { x: 1 } const A = Value.Pointer.Get(X, '/x') // const A = 1 const B = Value.Pointer.Get(X, '/y') // const B = undefined ``` -------------------------------- ### Compile and Parse User Schema Source: https://github.com/sinclairzx81/typebox/blob/main/readme.md Demonstrates compiling a TypeBox object schema for user data and then parsing an object against that schema. Ensure TypeBox is imported. ```typescript import Schema from 'typebox/schema' // Compile const User = Schema.Compile(Type.Object({ id: Type.String(), name: Type.String(), email: Type.String({ format: 'email' }) })) // Parse const user = User.Parse({ id: '65f1a2b3c4d5e6f7a8b9c0d1', name: 'user', email: 'user@domain.com' }) ``` -------------------------------- ### Create Value From Validator Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/compile/1_validator.html Creates a new value that conforms to the validator's schema. This is useful for generating default or example data. ```typescript const R = C.Create(value) ``` -------------------------------- ### Extension and Options Types Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/1_syntax.md Shows how to use extension types like Evaluate and Options with TypeBox Script. ```typescript const T16 = Type.Script('Evaluate<{ x: number } & { y: number }>') ``` ```typescript const T17 = Type.Script('Options<{ x: number }, { additionalProperties: false }>') ``` -------------------------------- ### Infer TypeScript Type from Number Schema Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/static.md Use Static to infer the TypeScript type for a simple number schema. No additional setup is required. ```typescript const T = Type.Number() type T = Static // type T = number ``` -------------------------------- ### Check if a string is a relative JSON Pointer Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/format/relative-json-pointer.md Use Format.IsRelativeJsonPointer to validate strings against the relative JSON Pointer format. No additional setup is required. ```typescript const R = Format.IsRelativeJsonPointer('0/name') ``` -------------------------------- ### Import Compile from TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/compile/overview.md Import the Compile function from the typebox/compile submodule. This is the first step to using the JIT compiler. ```typescript import { Compile } from 'typebox/compile' ``` -------------------------------- ### Create TypeBox Type with Options Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/2_options.md Shows how to create a TypeBox type using the Type.Options() function, mirroring the structure defined by Options for TypeScript compatibility. ```typescript const VectorA = Type.Options(Type.Object({ x: Type.Options(Type.Number(), { minimum: 0, maximum: 1 }), y: Type.Options(Type.Number(), { minimum: 0, maximum: 1 }) }), { additionalProperties: false }) ``` -------------------------------- ### Extract Function Parameters Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/parameters.md Use Type.Parameters to get the parameter types from a Function type. Ensure the input is a valid Function type definition. ```typescript const T = Type.Function([Type.String(), Type.Number()], Type.Object({})) const S = Type.Parameters(T) ``` -------------------------------- ### Initialize Google Analytics Source: https://github.com/sinclairzx81/typebox/blob/main/docs/index.html This snippet initializes Google Analytics by pushing the current date and configuration to the dataLayer. Ensure this code is included in your project's main script to enable analytics tracking. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-EYTCZ4PD6T'); ``` -------------------------------- ### Extract Constructor Parameters Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/constructor-parameters.md Use ConstructorParameters to get the parameter types from a Constructor type. This is useful for inferring types used in function signatures. ```typescript const T = Type.Constructor([Type.String(), Type.Number()], Type.Object({})) const S = Type.ConstructorParameters(T) ``` -------------------------------- ### Get Errors From Compiled Schema Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/schema/5_compile.md The Errors method of a compiled schema returns an array of validation errors. This is useful for debugging invalid data. ```typescript // ------------------------------------------------------------------ // Errors // ------------------------------------------------------------------ const E = C.Errors(T, { x: null }) // const E = [ // false, // [ // { // keyword: "required", // schemaPath: "#", // instancePath: "", // params: { requiredProperties: [ "y", "z" ] }, // message: "must have required properties y, z" // }, // { // keyword: "type", // schemaPath: "#/properties/x", // instancePath: "/x", // params: { type: "number" }, // message: "must be number" // } // ] // ] ``` -------------------------------- ### Create and Infer User Type Source: https://github.com/sinclairzx81/typebox/blob/main/readme.md This snippet demonstrates how to create a User type using TypeBox and infer its static type. It shows the TypeBox object definition and the corresponding static type inference. ```typescript import Type from 'typebox' // Type const User = Type.Object({ id: Type.String(), name: Type.String(), email: Type.String({ format: 'email' }) }) // Static type User = Type.Static ``` -------------------------------- ### Unsupported Template Literal Substring Infer Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/1_syntax.md TypeBox Script does not support substring inference with TemplateLiteral types. This example shows a construct that will not work. ```typescript type Get = S extends `hello ${infer Name}` ? Name : never // ^ // Substring infer not supported ``` -------------------------------- ### TypeBox Script Template Literal Type Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/1_syntax.md Defines a template literal type using Type.Script. This example shows a string with a union of numbers. ```typescript const T4 = Type.Script('`hello${1|2}`') // TTemplateLiteral<'^hello(1|2)$'> ``` -------------------------------- ### Mapped Type Expressions Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/1_syntax.md Shows how to create mapped types with and without key remapping using TypeBox Script. ```typescript const T2 = Type.Script(`{ [K in keyof 'x' | 'y' | 'z']: number }`) // TObject<{ x: TNumber, y: TNumber, z: TNumber // }> ``` ```typescript const T3 = Type.Script(`{ [K in keyof 'x' | 'y' | 'z' as Uppercase]?: number }`) // TObject<{ X: TOptional, Y: TOptional, Z: TOptional // }> ``` -------------------------------- ### TypeBox Encoder Pipeline Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/encode.md Illustrates the default encoder pipeline used by TypeBox, showing the order of operations including Clone, EncodeUnsafe, Default, Convert, Clean, and Assert. ```typescript const Encoder = Pipeline([ (_context, _type, value) => Clone(value), (context, type, value) => EncodeUnsafe(context, type, value), // <--- Encode First (context, type, value) => Default(context, type, value), (context, type, value) => Convert(context, type, value), (context, type, value) => Clean(context, type, value), (context, type, value) => Assert(context, type, value), ]) ``` -------------------------------- ### Basic JSON Schema Type Expressions Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html Illustrates the creation of basic JSON Schema types like any, unknown, never, boolean, integer, number, string, and null using Type.Script. ```typescript const T5 = Type.Script('any') // TAny const T6 = Type.Script('unknown') // TUnknown const T7 = Type.Script('never') // TNever const T8 = Type.Script('boolean') // TBoolean const T9 = Type.Script('integer') // TInteger const T10 = Type.Script('number') // TNumber const T11 = Type.Script('string') // TString const T12 = Type.Script('null') // TNull ``` -------------------------------- ### Initialize Google Analytics Data Layer Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/index.html This snippet initializes the Google Analytics data layer and configures tracking. Ensure this is included in your project's main HTML file. ```javascript window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-EYTCZ4PD6T'); ``` -------------------------------- ### Get Validation Errors Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/compile/1_validator.html Retrieves an array of validation errors for a given value against the validator's schema. Returns an empty array if the value is valid. ```typescript const R = C.Errors(value) ``` -------------------------------- ### Type.Array - Creating an Array Type Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/array.html Demonstrates how to create a TypeBox Array type with a specified item schema and shows the corresponding TypeScript type inference. ```APIDOC ## Type.Array ### Description Creates an Array type. ### Method Type.Array(schema, options?) ### Endpoint N/A (Client-side library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const T = Type.Array(Type.Number()) ``` ### Response #### Success Response (200) ```json { "type": "array", "items": { "type": "number" } } ``` #### Response Example ```typescript type T = number[] ``` ``` -------------------------------- ### Structural Type Expressions Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html Shows how to define structural types like objects and arrays using Type.Script. ```typescript const T17 = Type.Script('{ x: number }') // TObject<{ x: TNumber }> const T18 = Type.Script('[1, 2]') // TTuple<[TLiteral<1>, TLiteral<2>]> const T19 = Type.Script('number[]') // TArray ``` -------------------------------- ### Extract ReturnType from Function Schema Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/return-type.md Use Type.ReturnType to get the return type of a function schema. This is useful for defining schemas that represent function outputs. ```typescript const T = Type.Function([Type.String()], Type.Object({ x: Type.Number() })) const S = Type.ReturnType(T) // const S: TObject<{ // x: TNumber // }> ``` -------------------------------- ### Extract InstanceType from Constructor Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/instance-type.md Use Type.InstanceType to get the type of an instance created by a Type.Constructor. This is useful when you need to reference the shape of objects created by a constructor. ```typescript const T = Type.Constructor([Type.String()], Type.Object({ x: Type.Number() })) const S = Type.InstanceType(T) // const S: TObject<{ // x: TNumber // }> ``` -------------------------------- ### Define a Constructor Type Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html Use Type.Script to define a constructor type with specific parameters and return type. ```typescript const T23 = Type.Script(`new (a: number, b: number) => { foo: (x: string) => void bar: (x: string) => void baz: (x: string) => void }`) ``` -------------------------------- ### Reverse Tuple Elements with Script Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/4_advanced.md Use Script to reverse the order of elements within a tuple. This example defines a recursive type to achieve the reversal. ```typescript const Reverse = Type.Script(` = ( List extends [infer Head, ...infer Tail extends unknown[]] ? Reverse : Result )`) ``` ```typescript const Result = Type.Script({ Reverse }, `Reverse<[ 1, 2, 3, 4 ]>`) ``` -------------------------------- ### Extract Constructor Parameters Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/constructor-parameters.html Use ConstructorParameters to get the parameter types from a Constructor type. This is useful for defining function signatures or validating arguments passed to a constructor. ```typescript const T = Type.Constructor([Type.String(), Type.Number()], Type.Object({})) const S = Type.ConstructorParameters(T) ``` -------------------------------- ### Unwrap Promise Type with Type.Awaited Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/type/awaited.md Use Type.Awaited to get the type of the value a Promise will resolve to. This is useful when dealing with asynchronous operations and their expected return types. ```typescript const T = Type.Promise(Type.String()) const S = Type.Awaited(T) // const S: TString ``` -------------------------------- ### Log TypeBox Memory Metrics Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/system/3_memory.html Imports the Memory namespace from 'typebox/system' and logs the Metrics object to the console. This provides insights into allocation counts for various operations like assign, create, clone, discard, and update. ```javascript import { Memory } from 'typebox/system' console.log(Memory.Metrics) ``` -------------------------------- ### Get Errors from Validator Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/compile/1_validator.md Returns validation errors for a given value. If the value is valid, an empty array is returned. Assumes 'C' is a compiled Validator instance. ```typescript const R = C.Errors(value) ``` -------------------------------- ### TypeBox Decoder Pipeline Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/decode.md Illustrates the default Decoder pipeline used by Value.Decode, showing the sequence of validation and transformation steps. ```typescript const Decoder = Pipeline([ (_context, _type, value) => Clone(value), (context, type, value) => Default(context, type, value), (context, type, value) => Convert(context, type, value), (context, type, value) => Clean(context, type, value), (context, type, value) => Assert(context, type, value), (context, type, value) => DecodeUnsafe(context, type, value) // <--- Decode Last ]) ``` -------------------------------- ### Check for Json Pointer URI Fragment Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/format/json-pointer-uri-fragment.md Use this function to validate if a string is a valid RFC 6901 Json Pointer URI fragment. No additional setup is required. ```typescript const R = Format.IsJsonPointerUriFragment('#/paths/~1users/123') ``` -------------------------------- ### Custom Type Definition and Registration Source: https://github.com/sinclairzx81/typebox/blob/main/changelog/1.0.0-migration.md Illustrates the removal of TypeRegistry and the introduction of Type.Base for creating custom types without registration. ```typescript import { TypeRegistry, Kind, TSchema } from '@sinclair/typebox' // Definition interface TFoo extends TSchema { [Kind]: 'Foo' static: 'Foo' // Static } // Check TypeRegistry.Set('Foo', (value) => value === 'Foo') // Factory function Foo(): TFoo { return { [Kind]: 'Foo' } as never } ``` ```typescript import Type from '@sinclair/typebox' // Definition export class TFoo extends Type.Base<'Foo'> { // Static // Check public override Check(value: unknown): value is 'Foo' { return value === 'Foo' } } // Factory export function Foo(): TDate { return new TDate() } ``` -------------------------------- ### Extract Function ReturnType with Type.ReturnType Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/return-type.html Use Type.ReturnType to get the return type of a function schema. This is useful for creating new schemas based on existing function signatures. ```typescript const T = Type.Function([Type.String()], Type.Object({ x: Type.Number() })) const S = Type.ReturnType(T) // const S: TObject<{ // x: TNumber // }> ``` -------------------------------- ### Add Options to TypeBox Number With Script Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/2_options.md Demonstrates adding options to a TypeBox primitive type by passing the type as a string and options as an object to Type.Script(). ```typescript const B = Type.Script('number', { minimum: 0 maximum: 1 }) ``` -------------------------------- ### Extract InstanceType from Constructor Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/instance-type.html Use Type.InstanceType to get the type of the instance created by a Type.Constructor. This is useful for defining types that represent the shape of objects created by a constructor function. ```typescript const T = Type.Constructor([Type.String()], Type.Object({ x: Type.Number() })) const S = Type.InstanceType(T) ``` -------------------------------- ### TypeScript Emulation with TypeBox Script Source: https://github.com/sinclairzx81/typebox/blob/main/changelog/1.0.0.md Use Type.Script to emulate TypeScript types at runtime. This includes defining types, transforming them, and introspecting their properties. ```typescript // Script const T = Type.Script(`{ x: number, y: number, z: number }`) // Transform const S = Type.Script({ T }, `{ [K in keyof T as Uppercase]: T[K] | null }`) // Introspect S.properties.X.anyOf[0] // { type: 'number' } S.properties.X.anyOf[1] // { type: 'null' } ``` -------------------------------- ### Get Validation Errors from Compiled Schema Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/schema/5_compile.html The Errors method on the compiled schema object 'C' returns an array of validation errors. It takes the schema and the data to check as arguments. ```typescript // ------------------------------------------------------------------ // Errors // ------------------------------------------------------------------ const E = C.Errors(T, { x: null }) // const E = [ // false, // [ // { // keyword: "required", // schemaPath: "#", // instancePath: "", // params: { requiredProperties: [ "y", "z" ] }, // message: "must have required properties y, z" // }, // { // keyword: "type", // schemaPath: "#/properties/x", // instancePath: "/x", // params: { type: "number" }, // message: "must be number" // } // ] // ] ``` -------------------------------- ### Bailing Out of Inference for Large Types Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/5_scaling.html Demonstrates how to use `as never` to bail out of static inference for excessively large types, allowing runtime parsing but losing type inference. ```typescript const LargeType: TSchema = Type.Script(`{ x0: string, x1: string, x2: string, x3: string, // ... excessive properties x999999: string } ` as never) // bail out!! ``` -------------------------------- ### Import Value Module Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/overview.md Import the Value module from TypeBox. ```typescript import Value from 'typebox/value' ``` -------------------------------- ### Unsupported Embedded Function with Generic Type Parameter Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/1_syntax.md TypeBox Script does not support embedded function types that include generic type parameters. This example highlights an unsupported feature. ```typescript type Foo = { x: (value: T) => string } // ^ // Embedded generic function not supported ``` -------------------------------- ### Handle Ambiguous Constraints with Value.Create Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/create.md Value.Create throws an error if type constraints are ambiguous, like a String format without a default. Provide a default value to resolve this. ```typescript const T = Type.String({ format: 'email' }) const A = Value.Create(T) // throws CreateError ``` ```typescript const T = Type.String({ format: 'email', default: 'user@domain.com' }) const A = Value.Create(T) // const A: string = 'user@domain.com' ``` -------------------------------- ### Define an Interface with Heritage Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/interface.html Use Type.Interface to create an object schema that inherits from another interface. This example defines interface B which inherits from interface A and adds property 'b'. ```typescript const B = Type.Interface([A], { b: Type.Number() }) ``` -------------------------------- ### Create Object Instance with Default Value Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/value/create.html Use Value.Create to instantiate an object type. Default values are automatically applied. ```typescript const T = Type.Object({ x: Type.Number({ default: 42 }), y: Type.Number(), z: Type.Number() }) const A = Value.Create(T) // const A = { // x: 42, // y: 0, // z: 0 // } ``` -------------------------------- ### Inspect Memory Metrics Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/system/3_memory.md Imports the Memory namespace and logs its Metrics property to the console. This provides insights into allocation counts for various operations like assign, create, clone, discard, and update. ```typescript import { Memory } from 'typebox/system' console.log(Memory.Metrics) // { // assign: 42, // create: 459, // clone: 108, // discard: 97, // update: 11 // } ``` -------------------------------- ### Import TypeBox Format Module Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/format/overview.md Import the Format module for string format validation. This module is provided via optional import. ```typescript import Format from 'typebox/format' ``` -------------------------------- ### TypeScript Type Definition for Options Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/2_options.html Define a TypeScript type alias for `Options` to enable type sharing between TypeScript and TypeBox. This setup allows for consistent type definitions across environments. ```typescript type Options = Type ``` -------------------------------- ### Add Options to TypeBox Number Without Script Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/script/2_options.md Shows how to apply options like 'minimum' and 'maximum' directly to a TypeBox primitive type (e.g., Number) without using Type.Script. ```typescript const A = Type.Number({ minimum: 0 maximum: 1 }) ``` -------------------------------- ### Get TypeBox Refine Errors Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/type/refine.html This snippet shows how to use Value.Errors to check for validation errors against a TypeBox Refine type. It demonstrates how the custom error message is returned when the validation fails. ```typescript import { Value } from '@sinclair/typebox/value' const E = Value.Errors(Prime, 42) ``` -------------------------------- ### Embedded Generic Function Not Supported Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html The Sinclair ZX81 TypeBox implementation does not support embedded function types that use generic type parameters. This example illustrates a type definition that is not supported. ```typescript type Foo = { x: (value: T) => string } // ^ // Embedded generic function not supported ``` -------------------------------- ### Type.Codec and Type.Decode/Encode in TypeBox 1.0.0 Source: https://github.com/sinclairzx81/typebox/blob/main/changelog/1.0.0-migration.md Demonstrates bi-directional (Codec) and uni-directional (Decode/Encode) transformations in TypeBox version 1.0.0. ```typescript // Bi-Directional const NumberToString = Type.Codec(Type.Number()) .Decode(value => value.toString()) .Encode(value => parseFloat(value)) // Uni-Directional const NumberToStringDecode = Type.Decode(Type.Number(), value => value.toString()) const NumberToStringEncode = Type.Encode(Type.Number(), (value: number) => value.toString()) ``` -------------------------------- ### Template Literal Substring Infer Not Supported Source: https://github.com/sinclairzx81/typebox/blob/main/docs/docs/script/1_syntax.html The Sinclair ZX81 TypeBox implementation does not support inferring substrings from template literal types. This example shows a type definition that would fail. ```typescript type Get = S extends `hello ${infer Name}` ? Name : never // ^ // Substring infer not supported ``` -------------------------------- ### Define and Import Types with TypeBox Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/schema/6_advanced.md Defines static types for Vertex, Geometry, Material, and Mesh using TypeBox's `Type.Static` and imports common graphics types. ```typescript export type Vertex = Type.Static export type Geometry = Type.Static export type Material = Type.Static export type Mesh = Type.Static export const Vector2 = Import(GraphicsModule, 'Vector2') export const Vector3 = Import(GraphicsModule, 'Vector3') export const Vertex = Import(GraphicsModule, 'Vertex') export const Geometry = Import(GraphicsModule, 'Geometry') export const Material = Import(GraphicsModule, 'Material') export const Mesh = Import(GraphicsModule, 'Mesh') ``` -------------------------------- ### Value.Pointer.Set Source: https://github.com/sinclairzx81/typebox/blob/main/design/website/docs/value/pointer.md Updates a value at the specified JSON Pointer. If the path does not exist, it is created. ```APIDOC ## Value.Pointer.Set ### Description Updates a value at the given JSON Pointer. If the path does not exist, it is created. ### Method `Value.Pointer.Set(value: object, pointer: string, newValue: any): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const X = { x: 1 } Value.Pointer.Set(X, '/x', 100) // X' = { x: 100 } Value.Pointer.Set(X, '/y', 200) // X' = { x: 100, y: 200 } ``` ### Response #### Success Response (200) No content is returned, the object is modified in place. #### Response Example ```json // No response body ``` ```