Technical Documentation: sinclairzx81/typebox
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`readme.md`)
Install
$ npm install typeboxUsage
import Type from 'typebox'
const T = Type.Object({ // const T = {
x: Type.Number(), // type: 'object',
y: Type.Number(), // required: ['x', 'y', 'z']
z: Type.Number() // properties: {
}) // x: { type: 'number' },
// y: { type: 'number' },
// z: { type: 'number' }
// },
// }
type T = Type.Static<typeof T> // type T = {
// x: number,
// y: number,
// z: number
// }Overview
TypeBox is a runtime type system that creates in-memory JSON Schema objects that infer as TypeScript types. The schematics produced by this library are designed to match the static type checking rules of the TypeScript compiler. TypeBox offers a unified type that can be statically checked by TypeScript and runtime checked using standard JSON Schema validation.
This library is designed to allow JSON Schema to compose similar to how types compose within TypeScript's type system. It can be used as a simple tool to build up complex schematics or integrated into REST and RPC services to help validate data received over the wire.
License: MIT
Contents
Type
TypeBox types are JSON Schema fragments that compose into more complex types. The library provides a core set of types for constructing JSON Schema compliant schematics, alongside extended types designed to model constructs native to JavaScript and TypeScript. The JSON Schema schematics produced by TypeBox can be passed directly to any compliant validator.
Example
The following creates a User type and infers with Static.
import Type from 'typebox'
const User = Type.Object({ // const User = {
id: Type.String(), // type: 'object',
name: Type.String(), // required: [
email: Type.String({ format: 'email' }) // 'id',
}) // 'name',
// 'email'
// ],
// properties: {
// id: { type: 'string' },
// name: { type: 'string' },
// email: {
// type: 'string',
// format: 'email'
// }
// }
// }
type User = Type.Static<typeof User> // type User = {
// id: string,
// name: string,
// email: string
// }Script
Documentation | Example 1 | Example 2
TypeBox includes a micro TypeScript engine that can transform TypeScript definitions to JSON Schema. The engine is fully type-safe and supports many programmable constructs including Conditional, Mapped, Indexed, Generics, Distributive Generics, and more.
Example
Syntax highlighting is available via the Visual Studio Marketplace.
import Type from 'typebox'
const Math = Type.Script(`
type Vector4 = { x: number, y: number, z: number, w: number }
type Vector3 = { x: number, y: number, z: number }
type Vector2 = { x: number, y: number }
`)
const Graphics = Type.Script(Math, `
type Vertex = {
position: Vector4,
normal: Vector3,
uv: Vector2
}
type Geometry = {
vertices: Vertex[],
indices: number[]
}
type Material = {
ambient: Vector4,
diffuse: Vector4,
specular: Vector4
}
type Mesh = {
geometry: Geometry,
material: Material
}
`)
type Mesh = Type.Static<typeof Graphics['Mesh']> // type Mesh = {
// geometry: { ... },
// material: { ... }
// }Schema
Documentation | Example 1 | Example 2 | Example 3
TypeBox includes a high-performance JSON Schema JIT compiler that supports Draft 3 through to 2020-12. The compiler is designed to be a lightweight industry-grade alternative to Ajv and offers improved compilation and validation performance. It also offers automatic fallback to dynamic validation in JIT restricted environments such as Cloudflare Workers.
The compiler is available via optional sub module import.
import Schema from 'typebox/schema'Compile
The compiler accepts TypeBox types as well as plain JSON Schema objects, and returns a Validator instance which can be used to check values. The following compiles a Vector type.
import Schema from 'typebox/schema'
// Compile
const Vector = Schema.Compile(Type.Script(`{
x: number
y: number
z: number
}`))
// Check
const valid = Vector.Check({ x: 1, y: 0, z: 0 }) // const valid: boolean
// Parse
const result = Vector.Parse({ x: 1, y: 0, z: 0 }) // const result: {
// x: number
// y: number
// z: number
// }Compatibility
JSON Schema Test Suite | JSON Schema Compliance Suite
TypeBox supports all versions of JSON Schema and is heavily tested against the official JSON Schema Test Suite. It has high compatibility with modern specifications while also offering broad support for legacy versions if their semantics are not in conflict with modern specifications.
| Spec | 3 | 4 | 6 | 7 | 2019-09 | 2020-12 | v1 |
|---|---|---|---|---|---|---|---|
| additionalItems | ✅ | ✅ | ✅ | ✅ | ✅ | - | - |
| additionalProperties | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| allOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| anchor | - | - | - | - | ✅ | ✅ | ✅ |
| anyOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| boolean_schema | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| const | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| contains | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| content | - | - | - | - | ✅ | ✅ | ✅ |
| default | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| definitions | - | 1/2 | ✅ | ✅ | - | - | - |
| defs | - | - | - | - | ✅ | ✅ | - |
| dependencies | 17/18 | ✅ | ✅ | ✅ | - | - | - |
| dependentRequired | - | - | - | - | ✅ | ✅ | ✅ |
| dependentSchemas | - | - | - | - | ✅ | ✅ | ✅ |
| dynamicRef | - | - | - | - | - | ✅ | ✅ |
| enum | 16/18 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| exclusiveMaximum | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| exclusiveMinimum | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| if-then-else | - | - | - | ✅ | ✅ | ✅ | ✅ |
| infinite-loop-detection | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| items | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxContains | - | - | - | - | ✅ | ✅ | ✅ |
| maximum | 13/14 | 13/14 | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxItems | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxLength | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxProperties | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| minContains | - | - | - | - | ✅ | ✅ | ✅ |
| minimum | 12/13 | 16/17 | ✅ | ✅ | ✅ | ✅ | ✅ |
| minItems | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| minLength | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| minProperties | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| multipleOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| not | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| oneOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| pattern | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| patternProperties | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| prefixItems | - | - | - | - | - | ✅ | ✅ |
| properties | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| propertyNames | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| recursiveRef | - | - | - | - | ✅ | - | - |
| ref | 23/27 | 38/45 | 69/70 | 77/78 | ✅ | ✅ | ✅ |
| refRemote | 7/8 | 11/17 | ✅ | ✅ | ✅ | ✅ | ✅ |
| required | 3/4 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| type | 73/80 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| unevaluatedItems | - | - | - | - | ✅ | ✅ | ✅ |
| unevaluatedProperties | - | - | - | - | ✅ | ✅ | ✅ |
| uniqueItems | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Performance
TypeBox tracks performance against AJV8 only as the defacto performance standard. For broader comparative benchmarks, refer to the following community maintained projects.
Runtime Benchmarks | Schema Benchmarks
Compile
The following table shows compile performance for various JSON Schema structures. These benchmarks measure the time required to build and runtime JIT schematics. Faster compilation results in faster application startup.
┌──────────────────────┬──────────────┬──────────────┐
│ Compile │ TB1X │ AJV8 │
├──────────────────────┼──────────────┼──────────────┤
│ Boolean │ 54.9K ops/s │ 7K ops/s │
│ Number │ 154.2K ops/s │ 7.8K ops/s │
│ String │ 161.4K ops/s │ 9.7K ops/s │
│ Null │ 111.9K ops/s │ 8.9K ops/s │
│ Literal_String │ 34.6K ops/s │ 7.5K ops/s │
│ Literal_Number │ 78.1K ops/s │ 7.6K ops/s │
│ Literal_Boolean │ 79.7K ops/s │ 8.4K ops/s │
│ Pattern │ 92.1K ops/s │ 6.1K ops/s │
│ Object_Open │ 18.6K ops/s │ 1.3K ops/s │
│ Object_Close │ 17K ops/s │ 975 ops/s │
│ Object_Vector3 │ 33.3K ops/s │ 3.4K ops/s │
│ Object_Basis3 │ 18.9K ops/s │ 858 ops/s │
│ Intersect_And │ 63.5K ops/s │ 3.6K ops/s │
│ Intersect_Structural │ 25.7K ops/s │ 1.7K ops/s │
│ Union_Or │ 58.2K ops/s │ 3.3K ops/s │
│ Union_Structural │ 33.7K ops/s │ 2K ops/s │
│ Tuple_Values │ 19.5K ops/s │ 2K ops/s │
│ Tuple_Objects │ 4K ops/s │ 388 ops/s │
│ Array_Numbers_4 │ 90.7K ops/s │ 4.3K ops/s │
│ Array_Numbers_8 │ 121.8K ops/s │ 3.8K ops/s │
│ Array_Numbers_16 │ 116.6K ops/s │ 3.9K ops/s │
│ Array_Objects_Open │ 22.6K ops/s │ 802 ops/s │
│ Array_Objects_Close │ 18.4K ops/s │ 930 ops/s │
└──────────────────────┴──────────────┴──────────────┘Validate
The following table shows validation performance for various JSON Schema structures. These benchmarks measure overall validation throughput for compiled schematics.
┌──────────────────────┬──────────────┬──────────────┐
│ Validate │ TB1X │ AJV8 │
├──────────────────────┼──────────────┼──────────────┤
│ Boolean │ 192.2M ops/s │ 189.5M ops/s │
│ Number │ 112.4M ops/s │ 61M ops/s │
│ String │ 113.7M ops/s │ 64.1M ops/s │
│ Null │ 112.8M ops/s │ 64.9M ops/s │
│ Literal_String │ 108M ops/s │ 62.9M ops/s │
│ Literal_Number │ 113.5M ops/s │ 63.2M ops/s │
│ Literal_Boolean │ 109.2M ops/s │ 64.1M ops/s │
│ Pattern │ 26.5M ops/s │ 22.4M ops/s │
│ Object_Open │ 78M ops/s │ 47.2M ops/s │
│ Object_Close │ 38.6M ops/s │ 27.6M ops/s │
│ Object_Vector3 │ 91M ops/s │ 51.3M ops/s │
│ Object_Basis3 │ 41.1M ops/s │ 27.4M ops/s │
│ Intersect_And │ 107.6M ops/s │ 59.9M ops/s │
│ Intersect_Structural │ 83.6M ops/s │ 46.3M ops/s │
│ Union_Or │ 95M ops/s │ 7.9M ops/s │
│ Union_Structural │ 84.5M ops/s │ 52.3M ops/s │
│ Tuple_Values │ 74.7M ops/s │ 53M ops/s │
│ Tuple_Objects │ 32.9M ops/s │ 22.3M ops/s │
│ Array_Numbers_4 │ 93.3M ops/s │ 55.1M ops/s │
│ Array_Numbers_8 │ 90.3M ops/s │ 50.8M ops/s │
│ Array_Numbers_16 │ 76.8M ops/s │ 39.6M ops/s │
│ Array_Objects_Open │ 28.7M ops/s │ 20.4M ops/s │
│ Array_Objects_Close │ 10.3M ops/s │ 10.8M ops/s │
└──────────────────────┴──────────────┴──────────────┘Versions
TypeBox ships two distinct versions that span two generations of the TypeScript compiler.
| TypeBox | TypeScript | Description |
|---|---|---|
| 1.x | 6.0 - 7.0+ | Latest. Developed against the TypeScript 7 native compiler. Provides advanced type inference and native JSON Schema 2020-12 support. Includes backwards compatibility with 0.x types. ESM only. |
| 0.x | 5.0 - 6.0 | LTS. Developed against older TypeScript versions and actively maintained under Long Term Support. Compatible with both ESM and CJS. Issues should be submitted to the Sinclair TypeBox repository. |
Contribute
TypeBox is open to community contribution. Please ensure you submit an issue before submitting a pull request. The TypeBox project prefers open community discussion before accepting new features.
Overview (`example/mcp/readme.md`)
Mcp: ProtocolType
This example shows immediate inference and compilation of the official Mcp Protocol JSON Schema specification without an offline code generation step. The example is for reference purposes only and is used to demonstrate advanced JSON Schema inference cases for very large schematics.
Usage
The following compiles the CallToolRequest protocol definition and parses a value.
import { ProtocolValidator, type ProtocolType } from './mcp/index.ts'
// ------------------------------------------------------------------
// Type
// ------------------------------------------------------------------
type CallToolRequest = ProtocolType<'CallToolRequest'>
// ------------------------------------------------------------------
// Validator
// ------------------------------------------------------------------
const CallToolRequestValidator = ProtocolValidator('CallToolRequest')
// ------------------------------------------------------------------
// Parse
// ------------------------------------------------------------------
const callToolRequest = CallToolRequestValidator.Parse({
id: '...',
jsonrpc: '2.0',
method: 'tools/call',
params: {
_meta: {
'io.modelcontextprotocol/clientCapabilities': {},
'io.modelcontextprotocol/clientInfo': { name: '...', version: '...' },
'io.modelcontextprotocol/protocolVersion': '1',
},
name: 'add',
arguments: {
x: 1,
y: 2
}
}
})
// ------------------------------------------------------------------
// TypeSafe
// ------------------------------------------------------------------
callToolRequest.id // 'id'
callToolRequest.jsonrpc // '2.0'
callToolRequest.method // 'tools/call'
callToolRequest.params // { ... }Overview (`example/standard/readme.md`)
Standard Schema
A unified adapter that compiles TypeScript definitions, TypeBox types, or JSON Schema into a Standard Schema V1 compatible interface.
Usage
The adapter is a single StandardSchema function that will accept any of the three supported input formats and return a Standard Schema V1 interface. TypeScript inference is supported for all given inputs.
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Compile Overview (`design/website/docs/compile/overview.md`)
Compile
High Performance Runtime Validation
Overview
⚠️ Notice: The
typebox/compilesubmodule is being phased out in 1.x in favor of the more versatiletypebox/schemacompiler. Whiletypebox/compilewill be maintained throughout the 1.x release cycle, future development will focus on enhancing theschemasubmodule with advanced code generation and custom emit capabilities. Users are encouraged to migrate totypebox/schemaand provide feedback regarding feature parity or functional requirements.
The Compile submodule is a high-performance, JSON Schema-compliant JIT compiler that transforms schemas into efficient runtime validators. It is optimized for fast, dynamic schema compilation and delivers extremely high data-validation throughput.
import { Compile } from 'typebox/compile'Example
The following uses the compiler to Compile and Parse a value.
const C = Compile(Type.Object({ // const C: Validator<{}, TObject<{
x: Type.Number(), // x: TNumber,
y: Type.Number(), // y: TNumber,
z: Type.Number() // z: TNumber
})) // }>>
const A = C.Parse({ // const A: {
x: 0, // x: number,
y: 1, // y: number,
z: 0 // z: number
}) // } = ...Design Website Docs Format Overview (`design/website/docs/format/overview.md`)
Format
Standards-Based RFC String Validation
Overview
The Format module contains functions to validate string formats defined in Section 7.3 (Defined Formats) of the JSON Schema specification. These formats are integrated into TypeBox's JSON Schema validation infrastructure, but can also be used independently.
Example
The Format module is available via a submodule import.
import Format from 'typebox/format'
const A = Format.IsEmail('[email protected]') // trueDesign Website Docs Overview Overview (`design/website/docs/overview/overview.md`)
TypeBox
JSON Schema Type Builder with Static Type Resolution for TypeScript
Overview
TypeBox is a runtime type system that creates in-memory JSON Schema objects that infer as TypeScript types. The schematics produced by this library are designed to match the static type checking rules of the TypeScript compiler. TypeBox offers a unified type that can be statically checked by TypeScript and runtime checked using standard JSON Schema validation.
This library is designed to allow JSON Schema to compose similar to how types compose within TypeScript's type system. It can be used as a simple tool to build up complex schematics or integrated into REST and RPC services to help validate data received over the wire.
Type
The Type namespace creates JSON Schema.
import Type from 'typebox'
const T = Type.Object({ // const T = {
x: Type.Number(), // type: 'object',
y: Type.Number(), // required: ['x', 'y', 'z'],
z: Type.Number() // properties: {
}) // x: { type: 'number' },
// y: { type: 'number' },
// z: { type: 'number' }
// }
// }
type T = Type.Static<typeof T> // type T = {
// x: number,
// y: number,
// z: number
// }Script
The Script creates JSON Schema from TypeScript syntax.
import Type from 'typebox'
const T = Type.Script(`{
x: number
y: number
z: number
}`)
type T = Type.Static<typeof T> // type T = {
// x: number,
// y: number,
// z: number
// }
const S = Type.Script({ T }, `{
[K in keyof T]: T[K] | null
}`)
type S = Type.Static<typeof S> // type S = {
// x: number | null,
// y: number | null,
// z: number | null
// }Schema
The Schema module compiles schematics into high-performance validators.
import Type from 'typebox'
import Schema from 'typebox/schema'
const C = Schema.Compile(Type.Script(`{
x: number
y: number
z: number
}`))
const R = C.Parse(...) // const R: {
// x: number,
// y: number,
// z: number
// } = ...Design Website Docs Schema Overview (`design/website/docs/schema/overview.md`)
Schema
High Performance JSON Schema Compiler
Overview
TypeBox includes a high-performance JSON Schema JIT compiler that supports Draft 3 through to 2020-12. The compiler is designed to be a lightweight industry-grade alternative to Ajv and offers improved compilation and validation performance. It also offers automatic fallback to dynamic validation in JIT restricted environments such as Cloudflare Workers.
The compiler is available via optional sub module import.
import Schema from 'typebox/schema'Compile
The compiler accepts TypeBox types as well as plain JSON Schema objects, and returns a Validator instance which can be used to check values. The following compiles a Vector type.
import Schema from 'typebox/schema'
// Compile
const Vector = Schema.Compile(Type.Script(`{
x: number
y: number
z: number
}`))
// Check
const valid = Vector.Check({ x: 1, y: 0, z: 0 }) // const valid: boolean
// Parse
const result = Vector.Parse({ x: 1, y: 0, z: 0 }) // const result: {
// x: number
// y: number
// z: number
// }Design Website Docs Script Overview (`design/website/docs/script/overview.md`)
Script
TypeScript Engine for JSON Schema
Overview
TypeBox includes a micro TypeScript engine that can transform TypeScript definitions to JSON Schema. The engine is fully type-safe and supports many programmable constructs including Conditional, Mapped, Indexed, Generics, Distributive Generics, and more.
Example
Syntax highlighting is available via the Visual Studio Marketplace.
import Type from 'typebox'
const Math = Type.Script(`
type Vector4 = { x: number, y: number, z: number, w: number }
type Vector3 = { x: number, y: number, z: number }
type Vector2 = { x: number, y: number }
`)
const Graphics = Type.Script(Math, `
type Vertex = {
position: Vector4,
normal: Vector3,
uv: Vector2
}
type Geometry = {
vertices: Vertex[],
indices: number[]
}
type Material = {
ambient: Vector4,
diffuse: Vector4,
specular: Vector4
}
type Mesh = {
geometry: Geometry,
material: Material
}
`)
type Mesh = Type.Static<typeof Graphics['Mesh']> // type Mesh = {
// geometry: { ... },
// material: { ... }
// }Design Website Docs System Overview (`design/website/docs/system/overview.md`)
System
System Configuration
Overview
The System submodule contains global configurations for TypeBox. It is shared across other TypeBox submodules and is used to configure language locales, enforce immutable schemas, debug memory allocation and performance, or control general runtime characteristics of TypeBox's validation infrastructure.
Example
The following System namespaces are available.
import { Settings, Locale, Memory } from 'typebox/system'Design Website Docs Type Overview (`design/website/docs/type/overview.md`)
Type
JSON Schema Type Builder with Static Type Resolution for TypeScript
Overview
TypeBox types are JSON Schema fragments that compose into more complex types. The library provides a core set of types for constructing JSON Schema compliant schematics, alongside extended types designed to model constructs native to JavaScript and TypeScript. The JSON Schema schematics produced by TypeBox can be passed directly to any compliant validator.
Example
The following creates a User type and infers its TypeScript type with Static.
import Type from 'typebox'
const User = Type.Object({ // const User = {
id: Type.String(), // type: 'object',
name: Type.String(), // required: [
email: Type.String({ format: 'email' }) // 'id',
}) // 'name',
// 'email'
// ],
// properties: {
// id: { type: 'string' },
// name: { type: 'string' },
// email: {
// type: 'string',
// format: 'email'
// }
// }
// }
type User = Type.Static<typeof User> // type User = {
// id: string,
// name: string,
// email: string
// }Design Website Docs Value Overview (`design/website/docs/value/overview.md`)
Value
Functions to Process Dynamic JavaScript Values
Overview
The Value submodule provides functions for validation and other typed operations on JavaScript values. It includes functions such as Check, Parse, Clone, Encode, and Decode, as well as advanced functions for performing structural Diff and Patch operations on dynamic JavaScript values.
import Value from 'typebox/value'Example
The following uses the Value module to Parse a value.
const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
const A = Value.Parse(T, { // const A: {
x: 1, // x: number,
y: 0, // y: number,
z: 0 // z: number
}) // } = ...Manifest.Json (`docs/manifest.json`)
{
"compile": {
"0_compile": "docs/compile/0_compile.html",
"1_validator": "docs/compile/1_validator.html",
"2_code": "docs/compile/2_code.html",
"3_accelerate": "docs/compile/3_accelerate.html",
"overview": "docs/compile/overview.html"
},
"format": {
"1_registry": "docs/format/1_registry.html",
"date-time": "docs/format/date-time.html",
"date": "docs/format/date.html",
"duration": "docs/format/duration.html",
"email": "docs/format/email.html",
"hostname": "docs/format/hostname.html",
"idn-email": "docs/format/idn-email.html",
"idn-hostname": "docs/format/idn-hostname.html",
"ipv4": "docs/format/ipv4.html",
"ipv6": "docs/format/ipv6.html",
"iri-reference": "docs/format/iri-reference.html",
"iri": "docs/format/iri.html",
"json-pointer-uri-fragment": "docs/format/json-pointer-uri-fragment.html",
"json-pointer": "docs/format/json-pointer.html",
"overview": "docs/format/overview.html",
"regex": "docs/format/regex.html",
"relative-json-pointer": "docs/format/relative-json-pointer.html",
"time": "docs/format/time.html",
"uri-reference": "docs/format/uri-reference.html",
"uri-template": "docs/format/uri-template.html",
"uri": "docs/format/uri.html",
"url": "docs/format/url.html",
"uuid": "docs/format/uuid.html"
},
"overview": {
"1_install": "docs/overview/1_install.html",
"2_setup": "docs/overview/2_setup.html",
"3_versions": "docs/overview/3_versions.html",
"overview": "docs/overview/overview.html"
},
"schema": {
"1_check": "docs/schema/1_check.html",
"2_parse": "docs/schema/2_parse.html",
"3_errors": "docs/schema/3_errors.html",
"4_compile": "docs/schema/4_compile.html",
"5_meta": "docs/schema/5_meta.html",
"6_intern": "docs/schema/6_intern.html",
"7_compat": "docs/schema/7_compat.html",
"overview": "docs/schema/overview.html"
},
"script": {
"1_script": "docs/script/1_script.html",
"2_options": "docs/script/2_options.html",
"3_parameters": "docs/script/3_parameters.html",
"4_inference": "docs/script/4_inference.html",
"5_challenge": "docs/script/5_challenge.html",
"overview": "docs/script/overview.html"
},
"system": {
"1_settings": "docs/system/1_settings.html",
"2_locale": "docs/system/2_locale.html",
"3_memory": "docs/system/3_memory.html",
"overview": "docs/system/overview.html"
},
"type": {
"any": "docs/type/any.html",
"array": "docs/type/array.html",
"bigint": "docs/type/bigint.html",
"boolean": "docs/type/boolean.html",
"call": "docs/type/call.html",
"capitalize": "docs/type/capitalize.html",
"codec": "docs/type/codec.html",
"conditional": "docs/type/conditional.html",
"constructor-parameters": "docs/type/constructor-parameters.html",
"constructor": "docs/type/constructor.html",
"cyclic": "docs/type/cyclic.html",
"decode": "docs/type/decode.html",
"dependent": "docs/type/dependent.html",
"encode": "docs/type/encode.html",
"enum": "docs/type/enum.html",
"evaluate": "docs/type/evaluate.html",
"exclude": "docs/type/exclude.html",
"extract": "docs/type/extract.html",
"function": "docs/type/function.html",
"generic": "docs/type/generic.html",
"identifier": "docs/type/identifier.html",
"immutable": "docs/type/immutable.html",
"indexed": "docs/type/indexed.html",
"infer": "docs/type/infer.html",
"instance-type": "docs/type/instance-type.html",
"instantiate": "docs/type/instantiate.html",
"integer": "docs/type/integer.html",
"interface": "docs/type/interface.html",
"intersect": "docs/type/intersect.html",
"key-of": "docs/type/key-of.html",
"literal": "docs/type/literal.html",
"lowercase": "docs/type/lowercase.html",
"mapped": "docs/type/mapped.html",
"module": "docs/type/module.html",
"never": "docs/type/never.html",
"non-nullable": "docs/type/non-nullable.html",
"null": "docs/type/null.html",
"number": "docs/type/number.html",
"object": "docs/type/object.html",
"omit": "docs/type/omit.html",
"optional": "docs/type/optional.html",
"options": "docs/type/options.html",
"overview": "docs/type/overview.html",
"parameter": "docs/type/parameter.html",
"parameters": "docs/type/parameters.html",
"partial": "docs/type/partial.html",
"pick": "docs/type/pick.html",
"readonly-object": "docs/type/readonly-object.html",
"readonly": "docs/type/readonly.html",
"record": "docs/type/record.html",
"ref": "docs/type/ref.html",
"refine": "docs/type/refine.html",
"required": "docs/type/required.html",
"rest": "docs/type/rest.html",
"return-type": "docs/type/return-type.html",
"static": "docs/type/static.html",
"string": "docs/type/string.html",
"symbol": "docs/type/symbol.html",
"template-literal": "docs/type/template-literal.html",
"this": "docs/type/this.html",
"tuple": "docs/type/tuple.html",
"uncapitalize": "docs/type/uncapitalize.html",
"undefined": "docs/type/undefined.html",
"union": "docs/type/union.html",
"unknown": "docs/type/unknown.html",
"unsafe": "docs/type/unsafe.html",
"uppercase": "docs/type/uppercase.html",
"void": "docs/type/void.html",
"with": "docs/type/with.html"
},
"value": {
"assert": "docs/value/assert.html",
"check": "docs/value/check.html",
"clean": "docs/value/clean.html",
"clone": "docs/value/clone.html",
"convert": "docs/value/convert.html",
"create": "docs/value/create.html",
"decode": "docs/value/decode.html",
"default": "docs/value/default.html",
"diff": "docs/value/diff.html",
"encode": "docs/value/encode.html",
"equal": "docs/value/equal.html",
"errors": "docs/value/errors.html",
"hash": "docs/value/hash.html",
"mutate": "docs/value/mutate.html",
"overview": "docs/value/overview.html",
"parse": "docs/value/parse.html",
"patch": "docs/value/patch.html",
"pipeline": "docs/value/pipeline.html",
"pointer": "docs/value/pointer.html",
"repair": "docs/value/repair.html"
}
}
Design Website Docs Compile 0 Compile (`design/website/docs/compile/0_compile.md`)
Compile.Compile
The Compile function returns a new Validator instance.
Example
The following creates a Validator with Compile.
import { Compile } from 'typebox/compile'
const C = Compile(Type.Object({ // const C: Validator<{}, TObject<{
x: Type.Number(), // x: TNumber,
y: Type.Number(), // y: TNumber,
z: Type.Number() // z: TNumber
})) // }>>The following creates a Validator via constructor.
import { Validator } from 'typebox/compile'
const C = new Validator({}, Type.Object({ // const C: Validator<{}, TObject<{
x: Type.Number(), // x: TNumber,
y: Type.Number(), // y: TNumber,
z: Type.Number() // z: TNumber
})) // }>>Design Website Docs Compile 1 Validator (`design/website/docs/compile/1_validator.md`)
Compile.Validator
Validators provide optimized implementations of the functions available in the Value submodule.
Example
The following compiles a Validator and calls Check.
import { Compile, Validator } from 'typebox/compile'
const T = Compile(Type.Object({ // const T: Validator<{}, TObject<{
x: Type.Number(), // x: TNumber,
y: Type.Number(), // y: TNumber,
z: Type.Number(), // z: TNumber
})) // }>>
const R = T.Check({ x: 1, y: 2, z: 3 }) // const R: boolean = trueFunctions
The following functions are available on Validator instances.
Check
Checks a value matches a type.
const R = C.Check(value) // const R: booleanErrors
Returns the errors for the value, or an empty array if there are none.
const R = C.Errors(value) // const R: ValidationError[]Clean
Cleans a value
const R = C.Clean(value) // const R: unknownCode
Returns generated code for this Validator.
const R = C.Code() // const R: stringConvert
Converts a value
const R = C.Convert(value) // const R: unknownCreate
Creates a value of the Validator type
const R = C.Create(value) // const R: ...Decode
Decodes a value, running any Decode callbacks if available.
const R = C.Decode(value) // const R: ...Default
Creates defaults for the given value
const R = C.Default(value) // const R: unknownEncode
Encodes a value, running any Encode callbacks if available.
const R = C.Encode(value) // const R: ...IsAccelerated
Returns true if the Validator is using evaluated optimizations.
const R = C.IsAccelerated() // const R: booleanParse
Parses a value to the given type.
const R = C.Parse(value) // const R: ...Design Website Docs Compile 2 Code (`design/website/docs/compile/2_code.md`)
Compile.Code
The Code function is used to create standalone ESM validation modules that can be written to disk and imported as regular JavaScript modules. This function is an alternative to Compile and provides a way to achieve high throughput validation in Content Security Policy restricted environments.
CodeResult
The Code function returns a CodeResult structure that contains two properties, Code and External.
import { Code } from 'typebox/compile'
const result = Code(Type.String())
console.log(result.Code) // export function SetExternal(external) { ... }
//
// export function Check(value) { ... }
console.log(result.External) // { identifier: '...', variables: [...] }Design Website Docs Compile 3 Accelerate (`design/website/docs/compile/3_accelerate.md`)
Compile.Accelerate
TypeBox achieves high performance by compiling JSON schemas into optimized validation routines. The generated code is then evaluated at runtime within the environment, a technique known as Just-In-Time (JIT) compilation.
While TypeBox takes measures to ensure evaluation is safe, some environments do restrict runtime code evaluation by preventing calls to eval() or new Function(). In such cases, acceleration will not be possible. TypeBox will automatically fall back to interpreted dynamic checking if it detects a restrictive Content Security Policy.
IsAccelerated
You can check if a compiled Validator is using acceleration with the IsAccelerated function.
import { Compile } from 'typebox/compile'
const C = Compile(Type.String())
console.log(C.IsAccelerated()) // true if acceleratedDisable Acceleration
You can disable all acceleration with the following system setting.
import System from 'typebox/system'
System.Settings.Set({ useAcceleration: false }) // default is true
// ...
const C = Compile(Type.String())
console.log(C.IsAccelerated()) // will be falseDesign Website Docs Format 1 Registry (`design/website/docs/format/1_registry.md`)
Format.Registry
Custom string formats are supported with Get and Set.
Example
The following registers a hex-color format.
import Format from 'typebox/format'
// ------------------------------------------------------------------
// Set
// ------------------------------------------------------------------
Format.Set('hex-color', value => {
return /^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$/.test(value)
})
// ------------------------------------------------------------------
// Get
// ------------------------------------------------------------------
const IsHexColor = Format.Get('hex-color')
// ------------------------------------------------------------------
// Use
// ------------------------------------------------------------------
IsHexColor('#FF5733') // true
IsHexColor('#FFF') // true
IsHexColor('blue') // falseValidation
Once registered, custom formats become available to validators and can be referenced using the format keyword.
const T = Type.String({ format: 'hex-color' }) // const T = { type: 'string', format: 'hex-color' }
const R = Value.Check(T, '#FFFFFF') // true
const R = Value.Check(T, 'blue') // falseDesign Website Docs Format Date Time (`design/website/docs/format/date-time.md`)
Format.IsDateTime
Returns true if the string is an RFC 3339 date-time with optional RFC 9557 suffix.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsDateTime('2025-08-22T14:30:00Z')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'date-time' }, '2025-08-22T14:30:00Z')Design Website Docs Format Date (`design/website/docs/format/date.md`)
Format.IsDate
Returns true if the string is an RFC 3339 date component.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsDate('2025-08-22')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'date' }, '2025-08-22')Design Website Docs Format Duration (`design/website/docs/format/duration.md`)
Format.IsDuration
Returns true if the string is a duration conforming to RFC 3339, Appendix A.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsDuration('PT2H30M')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'duration' }, 'PT2H30M')Design Website Docs Format Email (`design/website/docs/format/email.md`)
Format.IsEmail
Returns true if the string is an email address conforming to RFC 5322.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsEmail('[email protected]')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'email' }, '[email protected]')Design Website Docs Format Hostname (`design/website/docs/format/hostname.md`)
Format.IsHostname
Returns true if the string is a hostname conforming to RFC 1123, with internationalized domain names supported by RFC 5891 and RFC 5892.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsHostname('example.com')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'hostname' }, 'example.com')Design Website Docs Format Idn Email (`design/website/docs/format/idn-email.md`)
Format.IsIdnEmail
Returns true if the string is an internationalized email address described by RFC 4952 and supported by the SMTP extension in RFC 6531.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsIdnEmail('사용자@예제.회사')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'idn-email' }, '사용자@예제.회사')Design Website Docs Format Idn Hostname (`design/website/docs/format/idn-hostname.md`)
Format.IsIdnHostname
Returns true if the string is an internationalized hostname described by RFC 5890, RFC 5891, RFC 5892, and RFC 5893.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsIdnHostname('예제.회사')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'idn-hostname' }, '예제.회사')Design Website Docs Format Ipv4 (`design/website/docs/format/ipv4.md`)
Format.IsIPv4
Returns true if the string is an IPv4 address as defined by RFC 3986, Section 3.2.2.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsIPv4('192.168.0.1')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'ipv4' }, '192.168.0.1')Design Website Docs Format Ipv6 (`design/website/docs/format/ipv6.md`)
Format.IsIPv6
Returns true if the string is an IPv6 address using the text representation defined in RFC 4291, Section 2.2.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsIPv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'ipv6' }, '2001:0db8:85a3:0000:0000:8a2e:0370:7334')Design Website Docs Format Iri Reference (`design/website/docs/format/iri-reference.md`)
Format.IsIriReference
Returns true if the string is an IRI reference as defined by RFC 3987.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsIriReference('https://예제.회사/경로')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'iri-reference' }, 'https://예제.회사/경로')Design Website Docs Format Iri (`design/website/docs/format/iri.md`)
Format.IsIri
Returns true if the string is an IRI as defined by RFC 3987.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsIri('https://예제.회사/경로')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'iri' }, 'https://예제.회사/경로')Design Website Docs Format Json Pointer Uri Fragment (`design/website/docs/format/json-pointer-uri-fragment.md`)
Format.IsJsonPointerUriFragment
Returns true if the string is a RFC 6901 JSON Pointer URI fragment.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsJsonPointerUriFragment('#/paths/~1users/123')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'json-pointer-uri-fragment' }, '#/paths/~1users/123')Design Website Docs Format Json Pointer (`design/website/docs/format/json-pointer.md`)
Format.IsJsonPointer
Returns true if the string is a RFC 6901 JSON Pointer.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsJsonPointer('/paths/~1users/123')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'json-pointer' }, '/paths/~1users/123')Design Website Docs Format Regex (`design/website/docs/format/regex.md`)
Format.IsRegex
Returns true if the string is a regular expression
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsRegex('^\\d{3}-\\d{2}-\\d{4}$')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'regex' }, '^\\d{3}-\\d{2}-\\d{4}$')Design Website Docs Format Relative Json Pointer (`design/website/docs/format/relative-json-pointer.md`)
Format.IsRelativeJsonPointer
Returns true if the string is a relative JSON Pointer as described in the IETF draft.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsRelativeJsonPointer('0/name')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'relative-json-pointer' }, '0/name')Design Website Docs Format Time (`design/website/docs/format/time.md`)
Format.IsTime
Returns true if the string is an RFC 3339 time component.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsTime('14:30:00Z')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'time' }, '14:30:00Z')Design Website Docs Format Uri Reference (`design/website/docs/format/uri-reference.md`)
Format.IsUriReference
Returns true if the string is a URI reference conforming to RFC 3986.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsUriReference('https://example.com/path')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'uri-reference' }, 'https://example.com/path')Design Website Docs Format Uri Template (`design/website/docs/format/uri-template.md`)
Format.IsUriTemplate
Returns true if the string is a RFC 6570 URI template.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsUriTemplate('https://example.com/{user}/profile')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'uri-template' }, 'https://example.com/{user}/profile')Design Website Docs Format Uri (`design/website/docs/format/uri.md`)
Format.IsUri
Returns true if the string is a URI conforming to RFC 3986.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsUri('https://example.com/path')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'uri' }, 'https://example.com/path')Design Website Docs Format Url (`design/website/docs/format/url.md`)
Format.IsUrl
Returns true if the string is a URL using the syntax defined by RFC 3986 and RFC 3987.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsUrl('https://example.com/path')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'url' }, 'https://example.com/path')Design Website Docs Format Uuid (`design/website/docs/format/uuid.md`)
Format.IsUuid
Returns true if the string is a UUID described by RFC 4122 and RFC 9562.
Function
Test with format function
import Format from 'typebox/format'
const R = Format.IsUuid('550e8400-e29b-41d4-a716-446655440000')Schema
Test with format keyword
import Schema from 'typebox/schema'
const R = Schema.Check({ format: 'uuid' }, '550e8400-e29b-41d4-a716-446655440000')Design Website Docs Overview 1 Install (`design/website/docs/overview/1_install.md`)
Install
TypeBox can be installed via npm.
Latest
Post-1.0 versions can be installed with the following.
$ npm install typebox --saveLegacy
Pre-1.0 versions can be installed with the following.
$ npm install @sinclair/typebox --saveDesign Website Docs Overview 2 Setup (`design/website/docs/overview/2_setup.md`)
Setup
The following is general information for setting up TypeBox
TsConfig (Required)
TypeBox requires the following tsconfig.json configuration
// file: tsconfig.json
{
"compilerOptions": {
"strict": true, // Required for Type Inference
"target": "ES2018", // Minimum ES Target
}
}Ajv (Optional)
The following is the recommended setup if using TypeBox with Ajv
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 = trueDesign Website Docs Overview 3 Versions (`design/website/docs/overview/3_versions.md`)
Versions
TypeBox provides two distinct versions, spanning two generations of the TypeScript compiler.
Version 0.x
$ npm install @sinclair/typebox # 0.x - LTS | TS 4-6Developed against TypeScript 4-6 and maintained under Long Term Support (LTS) for existing infrastructure on the 0.x revision line. ESM and CJS compatible.
Version 1.x
$ npm install typebox # 1.x - Latest | TS 7 NativeDeveloped against the TypeScript 7 native compiler with advanced type inference and JSON Schema 2020-12 compliant validation, with backwards compatibility for 0.x types. ESM only.
Additional
The 1.x version is recommended for most new projects and is the active development line that targets optimizations enabled by the TypeScript 7 native compiler. The 0.x version is maintained under LTS for environments requiring CJS and ESM compatibility as well as support for older TypeScript compiler versions. For issues relating to 0.x please submit them to the TypeBox 0.x repository.
Design Website Docs Schema 1 Check (`design/website/docs/schema/1_check.md`)
Schema.Check
The Check(...) function returns true if the value matches the schema.
Example
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
// ------------------------------------------------------------------
// Check
// ------------------------------------------------------------------
const R = Schema.Check(T, { x: 1, y: 2, z: 3 }) // const R: boolean = trueDesign Website Docs Schema 2 Parse (`design/website/docs/schema/2_parse.md`)
Schema.Parse
The Parse(...) function returns the value if it matches the schema; otherwise, it throws an error.
Example
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
// ------------------------------------------------------------------
// Parse
// ------------------------------------------------------------------
const R = Schema.Parse(T, { x: 1, y: 2, z: 3 }) // const R: {
// x: number,
// y: number,
// z: number
// } = ...Design Website Docs Schema 3 Errors (`design/website/docs/schema/3_errors.md`)
Schema.Errors
The Errors(...) function returns a tuple containing a boolean indicating whether the value is valid and an array of validation errors gathered up to the configured maxErrors limit. If the value is valid, the errors array is empty.
⚠️ For performance, this function should only be called after a failed Check. The function performs an exhaustive check up to the
maxErrorssetting (the default is8). For additional performance, consider reducingmaxErrorsto1, which will terminate gathering on the first error.
Example
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Schema 4 Compile (`design/website/docs/schema/4_compile.md`)
Schema.Compile
The Compile(...) function to compile JSON Schema into a high performance Validator.
Example
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Schema 5 Meta (`design/website/docs/schema/5_meta.md`)
Schema.Meta
JSON Schema is JSON like any other, and can be validated the same way. TypeBox includes meta schemas for the JSON Schema drafts it supports, letting you validate a schema against a specific draft version.
⚠️ TypeBox only includes meta schemas for published JSON Schema versions it tests against. Auxiliary schemas, such as OpenAPI or OpenRPC, can be passed to TypeBox but must be sourced separately.
Meta Schema Definitions
TypeBox provides inline definitions for the following JSON Schema draft meta schemas, also available at these URLs:
Usage
The example below parses a schema as Draft 2020-12, then validates a value against it. The meta schema is selected by its $schema identifier.
import Schema from 'typebox/schema'
// ------------------------------------------------------------------
// Validate Schema
// ------------------------------------------------------------------
const A = Schema.Parse(Schema.Meta['https://json-schema.org/draft/2020-12/schema'], {
type: 'object',
required: ['x', 'y', 'z'],
properties: {
x: { type: 'number' },
y: { type: 'number' },
z: { type: 'number' },
}
})
// ------------------------------------------------------------------
// Validate Value
// ------------------------------------------------------------------
const B = Schema.Parse(A, {
x: 1,
y: 2,
z: 3
})Design Website Docs Schema 6 Intern (`design/website/docs/schema/6_intern.md`)
Schema.Intern
The Intern(...) function is a JSON Schema optimizer that transforms schemas into fully referential structures with the same validation semantics as the original. It is similar in concept to Common Subexpression Elimination (CSE), where common subexpressions (subschemas in this case) are hoisted and globally referenced. TypeBox applies this concept to JSON Schema, enabling schema compression.
⚠️ The Intern(...) function is considered experimental. The function is tested against TypeBox-aware schemas and supports all JSON Schema keywords; however, full JSON Schema compliance testing is not yet complete. The recommendation is to use this function with Type.* and Script schemas only.
Intern Transform
The Intern(...) function restructures a JSON Schema to use $defs and content-addressed keys for each subschema. The resulting schema deduplicates structurally identical subschemas into shared $defs entries referenced via $ref, producing a compact, referential representation of the original schema. This can significantly reduce redundancy for large schemas.
/* Detailed source-code truncated for AI context efficiency. */Experimental Bytecode Inlining
The Intern(...) function was written to explore V8's optimizing compiler tier (Maglev), which inlines functions based on bytecode length. Interned schemas tend to produce smaller functions that are more likely to fall within fast optimization thresholds (typically a bytecode length around 27 to 30 depending on the runtime), and the reduced redundancy means less code for the engine to JIT overall (so faster JIT). The function can thus be thought of as an optional optimizing transform for TypeBox's compiler.
You can check the Maglev inlining thresholds with the following:
$ node --v8-options | grep max-inlined-bytecode-size-small
# --max-inlined-bytecode-size-small (maximum size of bytecode considered for small function inlining)
# type: int default: --max-inlined-bytecode-size-small=27The following example shows the transform and subsequent code generation with consideration to Maglev.
// ------------------------------------------------------------------
// Schema A
//
// When passing a non-referential schema to Schema.Compile(...), the
// result will be a single function with a large logical expression.
// Because a single expression may be long and complex, inlining
// optimizers may skip optimizations based on the engine's observed
// bytecode length.
//
// ------------------------------------------------------------------
const A = Type.Object({ // const A = {
x: Type.String(), // type: "object",
y: Type.Number(), // required: [ "x", "y", "z" ],
z: Type.Boolean() // properties: {
}) // x: { type: "string" },
// y: { type: "number" },
// z: { type: "boolean" }
// }
// }
// Expression may be considered too large for optimization.
Schema.Build(A).Functions() // const check_0 = ((value) => ((typeof value === "object"
// && value !== null && !(Array.isArray(value)))
// && ((("x" in value && "y" in value) && "z" in value)
// && ((typeof value.x === "string" && Number.isFinite(value.y))
// && typeof value.z === "boolean"))))The following shows the generated emit after an Intern(...) transformation.
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Schema 7 Compat (`design/website/docs/schema/7_compat.md`)
Schema.Compat
TypeBox supports all versions of JSON Schema and is heavily tested against the official JSON Schema Test Suite. It has high compatibility with modern specifications while also offering broad support for legacy versions if their semantics are not in conflict with modern specifications.
⚠️ TypeBox accepts schemas from any JSON Schema version, which means keywords from different versions can be mixed and matched freely. If an application needs to restrict schemas to a specific version, use the Schema.Meta namespace to validate them against that version.
Required Keywords
| Spec | 3 | 4 | 6 | 7 | 2019-09 | 2020-12 | v1 |
|---|---|---|---|---|---|---|---|
| additionalItems | ✅ | ✅ | ✅ | ✅ | ✅ | - | - |
| additionalProperties | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| allOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| anchor | - | - | - | - | ✅ | ✅ | ✅ |
| anyOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| boolean_schema | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| const | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| contains | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| content | - | - | - | - | ✅ | ✅ | ✅ |
| default | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| definitions | - | 1/2 | ✅ | ✅ | - | - | - |
| defs | - | - | - | - | ✅ | ✅ | - |
| dependencies | 17/18 | ✅ | ✅ | ✅ | - | - | - |
| dependentRequired | - | - | - | - | ✅ | ✅ | ✅ |
| dependentSchemas | - | - | - | - | ✅ | ✅ | ✅ |
| dynamicRef | - | - | - | - | - | ✅ | ✅ |
| enum | 16/18 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| exclusiveMaximum | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| exclusiveMinimum | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| if-then-else | - | - | - | ✅ | ✅ | ✅ | ✅ |
| infinite-loop-detection | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| items | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxContains | - | - | - | - | ✅ | ✅ | ✅ |
| maximum | 13/14 | 13/14 | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxItems | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxLength | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxProperties | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| minContains | - | - | - | - | ✅ | ✅ | ✅ |
| minimum | 12/13 | 16/17 | ✅ | ✅ | ✅ | ✅ | ✅ |
| minItems | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| minLength | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| minProperties | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| multipleOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| not | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| oneOf | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| pattern | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| patternProperties | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| prefixItems | - | - | - | - | - | ✅ | ✅ |
| properties | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| propertyNames | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| recursiveRef | - | - | - | - | ✅ | - | - |
| ref | 23/27 | 38/45 | 69/70 | 77/78 | ✅ | ✅ | ✅ |
| refRemote | 7/8 | 11/17 | ✅ | ✅ | ✅ | ✅ | ✅ |
| required | 3/4 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| type | 73/80 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| unevaluatedItems | - | - | - | - | ✅ | ✅ | ✅ |
| unevaluatedProperties | - | - | - | - | ✅ | ✅ | ✅ |
| uniqueItems | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Optional Keywords and Proposals
| Spec | 3 | 4 | 6 | 7 | 2019-09 | 2020-12 | v1 |
|---|---|---|---|---|---|---|---|
| anchor | - | - | - | - | ✅ | ✅ | ✅ |
| bignum | 7/9 | 7/9 | ✅ | ✅ | ✅ | ✅ | ✅ |
| content | - | - | - | 6/10 | - | - | - |
| cross-draft | - | - | - | ✅ | 2/3 | 0/1 | - |
| dependencies-compatibility | - | - | - | - | ✅ | ✅ | ✅ |
| dynamicRef | - | - | - | - | - | ✅ | ✅ |
| ecmascript-regex | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| float-overflow | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| format-annotation | - | - | - | - | - | - | 114/133 |
| format-assertion | - | - | - | - | - | ✅ | - |
| format/color | 3/6 | - | - | - | - | - | - |
| format/date | ✅ | - | - | ✅ | ✅ | ✅ | ✅ |
| format/date-time | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/duration | - | - | - | - | ✅ | ✅ | ✅ |
| format/ecmascript-regex | ✅ | - | - | ✅ | ✅ | ✅ | ✅ |
| format/email | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/host-name | 2/12 | - | - | - | - | - | - |
| format/hostname | - | 30/31 | 30/31 | ✅ | ✅ | ✅ | ✅ |
| format/idn-email | - | - | - | ✅ | ✅ | ✅ | ✅ |
| format/idn-hostname | - | - | - | ✅ | ✅ | ✅ | ✅ |
| format/ip-address | 1/3 | - | - | - | - | - | - |
| format/ipv4 | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/ipv6 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/iri | - | - | - | ✅ | ✅ | ✅ | ✅ |
| format/iri-reference | - | - | - | ✅ | ✅ | ✅ | ✅ |
| format/json-pointer | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/regex | ✅ | - | - | ✅ | ✅ | ✅ | ✅ |
| format/relative-json-pointer | - | - | - | ✅ | ✅ | ✅ | ✅ |
| format/time | 2/3 | - | - | ✅ | ✅ | ✅ | 49/55 |
| format/unknown | - | ✅ | ✅ | ✅ | ✅ | ✅ | - |
| format/uri | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/uri-reference | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/uri-template | - | - | ✅ | ✅ | ✅ | ✅ | ✅ |
| format/uuid | - | - | - | - | ✅ | ✅ | ✅ |
| id | - | 2/3 | ✅ | ✅ | ✅ | ✅ | ✅ |
| no-schema | - | - | - | - | ✅ | ✅ | - |
| non-bmp-regex | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| proposals/propertyDependencies/additionalProperties | - | - | - | - | - | - | ✅ |
| proposals/propertyDependencies/dynamicRef | - | - | - | - | - | - | 4/8 |
| proposals/propertyDependencies/propertyDependencies | - | - | - | - | - | - | 17/21 |
| proposals/propertyDependencies/unevaluatedProperties | - | - | - | - | - | - | 4/6 |
| refOfUnknownKeyword | - | - | - | - | ✅ | ✅ | ✅ |
| unknownKeyword | - | - | 1/3 | 1/3 | 1/3 | 1/3 | 1/3 |
| zeroTerminatedFloats | 0/1 | 0/1 | - | - | - | - | - |
Design Website Docs Script 1 Script (`design/website/docs/script/1_script.md`)
Script.Script
The Script function is designed to be a programmable TypeScript DSL frontend for the JSON Schema specification. Internally it uses TypeBox types as an intermediate representation (IR) for TypeScript, where the IR itself is expressed as standards-compliant JSON Schema.
// The Script function returns JSON Schema
const A = Type.Script('string') // const A = { type: 'string' }Types
Script has support for most TypeScript types and programmable constructs.
/* Detailed source-code truncated for AI context efficiency. */Type Expressions
Script provides support for most TypeScript type-level expressions.
/* Detailed source-code truncated for AI context efficiency. */Type Augmentation
Script supports extended syntax to augment types with constraints and annotations.
/* Detailed source-code truncated for AI context efficiency. */Built In Types
Script includes support for most TypeScript utility types and intrinsics.
// ------------------------------------------------------------------
// Utility Types
// ------------------------------------------------------------------
const T0 = Type.Script(`Partial<{ x: number }>`)
const T1 = Type.Script(`Required<{ x: number }>`)
const T2 = Type.Script(`Readonly<{ x: number }>`)
const T3 = Type.Script(`Pick<{ x: number, y: number }, 'x'>`)
const T4 = Type.Script(`Omit<{ x: number, y: number }, 'x'>`)
const T5 = Type.Script(`NonNullable<string | null>`)
const T6 = Type.Script('Exclude<1 | 2 | 3, 1 | 2>')
const T7 = Type.Script('Extract<1 | 2 | 3, 1 | 2>')
const T8 = Type.Script('ConstructorParameters<new (x: number) => {}>')
const T9 = Type.Script('Parameters<(x: number) => number>')
const T10 = Type.Script('ReturnType<(x: number) => number>')
const T11 = Type.Script('InstanceType<new (x: number) => {}>')
// ------------------------------------------------------------------
// Intrinsic String Manipulation
// ------------------------------------------------------------------
const T12 = Type.Script('Uppercase<"hello">')
const T13 = Type.Script('Lowercase<"hello">')
const T14 = Type.Script('Capitalize<"hello">')
const T15 = Type.Script('Uncapitalize<"hello">')
// ------------------------------------------------------------------
// Extension Types
// ------------------------------------------------------------------
const T16 = Type.Script('Evaluate<{ x: number } & { y: number }>')Type Modules
The Script function also accepts type and interface declarations. The return value will be an object containing all embedded declarations.
const { Expression, ConstDeclaration, BinaryExpression, ConstExpression } = Type.Script(`
type Expression =
| ConstDeclaration
| BinaryExpression
| ConstExpression
interface ConstDeclaration {
type: 'ConstDeclaration'
name: string
value: Expression
}
interface BinaryExpression {
type: 'BinaryExpression'
left: Expression
right: Expression
}
interface ConstExpression {
type: 'ConstExpression'
const: unknown
}
`)Unsupported
The following constructs are currently unsupported.
Template Literal Substring Infer
Script does not support substring inference with TemplateLiteral types.
type Get<S extends string> = S extends `hello ${infer Name}` ? Name : never
// ^
// Substring infer not supportedEmbedded Function with Generic Type Parameter
Script does not support embedded function types with generic type parameters.
type Foo = { x: <T>(value: T) => string }
// ^
// Embedded generic function not supportedDesign Website Docs Script 2 Options (`design/website/docs/script/2_options.md`)
Script.Options
Script types can be assigned options using the with keyword.
With Keyword
The with keyword assigns arbitrary metadata directly to a type.
const Email = Type.Script(`string with { format: 'email' }`)
// Produces
const Email = { type: 'string', format: 'email' }The same syntax extends to multiple embedded types within a single declaration.
const Vector = Type.Script(`{
x: number with { minimum: 0, maximum: 1 },
y: number with { minimum: 0, maximum: 1 },
z: number with { minimum: 0, maximum: 1 },
} with { additionalProperties: false }`)It works equally well within computed type expressions, such as mapped types.
const { Vector, ClampedVector } = Type.Script(`
type Vector = {
x: number
y: number
z: number
}
type Clamp<T> = {
[K in keyof T]: T[K] with { minimum: 0, maximum: 1 }
} with { additionalProperties: false }
type ClampedVector = Clamp<Vector>
`)With Function
The with keyword is a syntactic alias for the With function.
const Email = Type.With(Type.String(), { format: 'email' })Design Website Docs Script 3 Parameters (`design/website/docs/script/3_parameters.md`)
Script.Parameters
Script can accept external types using a leading context argument.
Parameters
The following creates a nullable string by passing an external string into the Script.
const T = Type.String()
const S = Type.Script({ T }, `T | null`) // const S: TUnion<[
// TString,
// TNull
// ]>Multiple external types can be passed via the context object.
const A = Type.Literal(1)
const B = Type.Literal(2)
const C = Type.Literal(3)
const T = Type.Script({ A, B, C }, `[A, B, C]`) // const T: TTuple<[
// TLiteral<1>,
// TLiteral<2>,
// TLiteral<3>
// ]>Module Dependencies
Script modules can be passed as the context for other modules, allowing type definitions to be shared across dependent modules.
import Type from 'typebox'
const Math = Type.Script(`
type Vector4 = { x: number, y: number, z: number, w: number }
type Vector3 = { x: number, y: number, z: number }
type Vector2 = { x: number, y: number }
`)
const Graphics = Type.Script(Math, `
type Vertex = {
position: Vector4,
normal: Vector3,
uv: Vector2
}
type Geometry = {
vertices: Vertex[],
indices: number[]
}
type Material = {
ambient: Vector4,
diffuse: Vector4,
specular: Vector4,
}
type Mesh = {
geometry: Geometry
material: Material
}
`)
type Mesh = Type.Static<typeof Graphics['Mesh']> // type Mesh = {
// geometry: { ... },
// material: { ... }
// }Design Website Docs Script 4 Inference (`design/website/docs/script/4_inference.md`)
Script.Inference
TypeBox Script is a dual-track (symmetric) runtime and type-level evaluator for TypeScript syntax. The runtime track can evaluate moderately large TypeScript definitions; however, the type-level track is subject to the instantiation limitations of the TypeScript compiler. This section details inference scaling and limitations for the type-level track based on default TypeScript language service settings.
Wide vs Deep
Script is designed to support wide data structures. These structures use TypeScript tail call optimizations to prevent +1 depth per sequence token or element.
const T = Type.Script(`[ // depth + 1
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,
]`)However, deeply nested structures will hit TypeScript instantiation depth limits very quickly.
const T = Type.Script(`{ // depth + 1
a: { // depth + 2
b: { // depth + 3
c: { // depth + 4
d: { // error: instantiation too deep
e: 1
}
}
}
}
}`)If you need to represent deep structures with Script, consider refactoring in the following way.
const D = Type.Script(`{ e: 1 }`) // depth + 1
const C = Type.Script({ D }, `{ d: D }`) // depth + 1
const B = Type.Script({ C }, `{ c: C }`) // depth + 1
const A = Type.Script({ B }, `{ b: B }`) // depth + 1
const T = Type.Script({ A }, `{ a: A }`) // okExcessive Types
Script supports static inference for moderately sized types, but for very large types, you will likely need to bail out of inference. This can be done by using an as never assertion. The Script will parse the type at runtime, but type inference will be lost.
⚠️ For large types it is recommended to use the standard Type API.
const LargeType: TSchema = Type.Script(`{
x0: string,
x1: string,
x2: string,
x3: string,
// ... excessive properties
x999999: string
}
` as never) // bail outDesign Website Docs Script 5 Challenge (`design/website/docs/script/5_challenge.md`)
Script.Challenge
TypeBox Script enables type-level programming in runtime environments. This page collects TypeBox solutions to problems from the community-run Type Challenges project. These solutions are used to track functional parity with TypeScript.
Solutions
Solutions to Type Challenges implemented with TypeBox's scripting engine. These solutions can also be used as a reference for writing type-level programs in TypeBox.
Design Website Docs System 1 Settings (`design/website/docs/system/1_settings.md`)
System.Settings
The Settings namespace manages global TypeBox configurations.
Example
The following shows general usage
import System from 'typebox/system'
// Apply freeze to schemas on creation
System.Settings.Set({ immutableTypes: true })
Type.String().format = 'email' // Error: Cannot add property format, object is not extensible
// Reset to defaults
System.Settings.Reset()The following settings are available.
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs System 2 Locale (`design/website/docs/system/2_locale.md`)
System.Locale
TypeBox provides error message translation (i18n) support for over 40 languages.
Example
TypeBox uses ISO 639-1 language region codes for each Locale. They can be set in the following way.
import System, { Locale } from 'typebox/system'
System.Locale.Set(Locale.en_US) // English - United States
System.Locale.Set(Locale.ko_KR) // Korean - South Korea
System.Locale.Set(Locale.fr_FR) // French - France
System.Locale.Set(Locale.zh_Hant) // Chinese - TraditionalErrors
Set the Locale immediately before calling Errors to generate messages for that locale.
import System, { Locale } from 'typebox/system'
import Schema from 'typebox/schema'
import Type from 'typebox'
System.Locale.Set(Locale.fr_FR) // French - France
const E = Schema.Errors(Type.Number(), 'not-number') // const E = [false, {
// keyword: "type",
// schemaPath: "#/type",
// instancePath: "",
// params: { type: "number" },
// message: "doit être number"
// }]Design Website Docs System 3 Memory (`design/website/docs/system/3_memory.md`)
System.Memory
The Memory namespace is used to allocate schemas with enumerable and non-enumerable properties, as well as track allocations made by the type system.
Metrics
The Memory namespace includes a Metrics property that tracks allocations created within the type system. You can use this property to inspect memory usage, debug, or gain insights into the allocations required during instantiation.
import System from 'typebox/system'
import Type from 'typebox'
// --------------------------------------------------------
// Computed Type
// --------------------------------------------------------
const Reverse = Type.Script(`<T, Result extends unknown[] = []> = (
T extends [infer L, ...infer R]
? Reverse<R, [L, ...Result]>
: Result
)`)
const Result = Type.Script({ Reverse }, `Reverse<[
1, 2, 3, 4, 5, 6, 7, 8
]>`) // TTuple<[
// TLiteral<8>,
// TLiteral<7>,
// ...
// TLiteral<1>
// ]>
// --------------------------------------------------------
// Inspect
// --------------------------------------------------------
console.log(System.Memory.Metrics) // {
// assign: 42,
// create: 459,
// clone: 108,
// discard: 97,
// update: 11
// }Design Website Docs Type Any (`design/website/docs/type/any.md`)
Type.Any
Creates an Any type.
Example
Example usage is shown below.
const T = Type.Any() // const T = {}
type T = Static<typeof T> // type T = anyGuard
Use the IsAny function to guard values of this type.
Type.IsAny(value) // value is TAnyDesign Website Docs Type Array (`design/website/docs/type/array.md`)
Type.Array
Creates an Array type.
Example
Example usage is shown below.
const T = Type.Array(Type.Number()) // const T = {
// type: 'array',
// items: {
// type: 'number',
// }
// }
type T = Static<typeof T> // type T = number[]Guard
Use the IsArray function to guard values of this type.
Type.IsArray(value) // value is TArrayOptions
export interface TArrayOptions extends TSchemaOptions {
/**
* The minimum number of items allowed in the array.
*/
minItems?: number
/**
* The maximum number of items allowed in the array.
*/
maxItems?: number
/**
* A schema that at least one item in the array must validate against.
*/
contains?: TSchema
/**
* The minimum number of array items that must validate against the `contains` schema.
*/
minContains?: number
/**
* The maximum number of array items that may validate against the `contains` schema.
*/
maxContains?: number
/**
* An array of schemas, where each schema in `prefixItems` validates against items at corresponding positions from the beginning of the array.
*/
prefixItems?: TSchema[]
/**
* If `true`, all items in the array must be unique.
*/
uniqueItems?: boolean
}Design Website Docs Type Bigint (`design/website/docs/type/bigint.md`)
Type.BigInt
Creates a BigInt type.
⚠️ This type cannot be expressed in standard JSON Schema. Do not use it if publishing types for other languages to consume.
Example
Example usage is shown below.
const T = Type.BigInt() // const T = {
// type: 'bigint'
// }
type T = Static<typeof T> // type T = bigintGuard
Use the IsBigInt function to guard values of this type.
Type.IsBigInt(value) // value is TBigIntDesign Website Docs Type Boolean (`design/website/docs/type/boolean.md`)
Type.Boolean
Creates a Boolean type.
Example
Example usage is shown below.
const T = Type.Boolean() // const T = { type: 'boolean' }
type T = Static<typeof T> // type T = booleanGuard
Use the IsBoolean function to guard values of this type.
Type.IsBoolean(value) // value is TBooleanDesign Website Docs Type Call (`design/website/docs/type/call.md`)
Type.Call
The Call function invokes Generic type.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const G = Type.Generic([
Type.Parameter('T')
], Type.Array(Type.Ref('T')))
const S = Type.Call(G, [Type.Number()]) // const S: TArray<TNumber>Guard
Use the IsCall function to guard values of this type.
Type.IsCall(value) // value is TCallDesign Website Docs Type Capitalize (`design/website/docs/type/capitalize.md`)
Type.Capitalize
The Capitalize function will capitalize string literals.
Example
Example usage is shown below.
const T = Type.Literal('hello')
const S = Type.Capitalize(T) // const S: TLiteral<'Hello'>Design Website Docs Type Codec (`design/website/docs/type/codec.md`)
Type.Codec
The Codec function applies a bi-directional transform codec to a type.
Example
The following creates a Codec that transforms a timestamp into a Date object.
const Timestamp = Type.Codec(Type.Integer()) // const Timestamp = {
.Decode(value => new Date(value)) // type: 'integer',
.Encode(value => value.getTime()) // '~codec': {
// decode: value => new Date(),
// encode: value => value.getTime()
// }
// }
// Use Value.Decode() and Value.Encode() to run Decode and Encode callbacks.
const D = Value.Decode(Timestamp, 12345) // const D = 1970-01-01T00:00:12.345Z
const E = Value.Encode(Timestamp, D) // const E = 12345Static
Use the StaticDecode and StaticEncode types that infer the Decoded and Encoded state of a type.
import Type, { type StaticEncode, type StaticDecode } from 'typebox'
const Timestamp = Type.Codec(Type.Integer())
.Decode(value => new Date(value))
.Encode(value => value.getTime())
type D = StaticDecode<typeof Timestamp> // type D = Date
type E = StaticEncode<typeof Timestamp> // type E = numberDesign Website Docs Type Conditional (`design/website/docs/type/conditional.md`)
Type.Conditional
Creates a conditional type expression.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const L = Type.Literal(1)
const R = Type.Number()
const T = Type.Conditional(L, R, // const T: TLiteral<true>
Type.Literal(true),
Type.Literal(false)
)Design Website Docs Type Constructor Parameters (`design/website/docs/type/constructor-parameters.md`)
Type.ConstructorParameters
The ConstructorParameters function will extract Parameters from a Constructor type.
Example
Example usage is shown below.
const T = Type.Constructor([Type.String(), Type.Number()], Type.Object({}))
const S = Type.ConstructorParameters(T) // const S: TTuple<[
// TString,
// TNumber
// ]>Design Website Docs Type Constructor (`design/website/docs/type/constructor.md`)
Type.Constructor
Creates a Constructor type.
⚠️ This type is used for interface definitions and cannot be validated.
Example
Example usage is shown below.
const T = Type.Constructor([ // const T = {
Type.String(), // type: 'constructor'
Type.Boolean(), // parameters: [
], Type.Object({ // { type: 'string' },
x: Type.Number() // { type: 'boolean' }
})) // ],
// instanceType: {
// type: 'object',
// required: ['x'],
// properties: {
// x: { type: 'number' }
// }
// }
// }
type T = Static<typeof T> // type T = new (
// args_0: string,
// args_1: boolean
// ) => {
// x: number
// }Guard
Type.IsConstructor(value) // value is TConstructor<TSchema[], TSchema>Design Website Docs Type Cyclic (`design/website/docs/type/cyclic.md`)
Type.Cyclic
Creates a Cyclic type. A Cyclic is a self-contained schema for potentially recursive types. It holds one or more named definitions in a $defs map and uses a $ref to select the root definition. Because references resolve against these definitions, a definition can refer to itself or another definition without depending on an external schema. Cyclic types are typically produced by Script when a declaration is recursive, but can also be created directly with Cyclic.
Example
Example usage is shown below.
const T = Type.Cyclic({ // const T = {
A: Type.Object({ // '$defs': {
x: Type.Array(Type.Ref('A')), // A: {
}), // type: 'object',
}, 'A') // required: [ 'x' ],
// properties: {
// x: {
// type: 'array',
// items: {
// '$ref': 'A'
// }
// }
// },
// '$id': 'A'
// }
// },
// '$ref': 'A'
// }
type T = Static<typeof T> // type T = { x: ...[] }Guard
Use the IsCyclic function to guard values of this type.
Type.IsCyclic(value) // value is TCyclicDeclarations
The Cyclic type is a container that bundles a recursive type with the definitions it depends on, producing a self-contained schema. It is intended to be the result structure for multi-type declarations, where one declaration may depend on another. This ensures each returned schema is self-contained, meaning all of its references resolve within the type itself.
The need for Cyclic is easiest to explain with an example. Consider the following two declarations: Vector is acyclic and has no dependencies, while Node is recursive and depends on Vector. Note that Node is inferred as a TCyclic to ensure it is self-contained.
import Type from 'typebox'
// Each declaration is returned as a standalone type
const { Vector, Node } = Type.Script(`
type Vector = {
x: number
y: number
z: number
}
type Node = {
id: string
value: Vector
nodes: Node[] // <-- Node is recursive, so it infers as TCyclic
}
`)Vector
The Vector type is acyclic and has no dependencies, so it can be returned as is.
const Vector: Type.TObject<{
x: Type.TNumber;
y: Type.TNumber;
z: Type.TNumber;
}>Node
The Node type references itself and depends on Vector, so it must be transformed into a TCyclic to be self-contained. The Vector dependency is collected and included as a definition within the TCyclic, and references inside Node resolve against those definitions. The second type argument ("Node") identifies the root definition.
const Node: Type.TCyclic<{
Node: Type.TObject<{
id: Type.TString;
nodes: Type.TArray<Type.TRef<"Node">>;
value: Type.TRef<"Vector">;
}>;
Vector: Type.TObject<{
x: Type.TNumber;
y: Type.TNumber;
z: Type.TNumber;
}>;
}, "Node">Embedding
The output structure of a TCyclic is a flat $defs and $ref structure. It can safely reference only structures downstream of itself, and it has no information about potential parent types. Because of this, embedding a Cyclic in an enclosing type is generally considered unsafe.
Unsafe
Here, the Node type produces a Cyclic, which we embed in a parent Container type. This composition works in this example, but it is not always safe: duplicate or overridden $id values can cause references to resolve to the wrong target. We therefore consider this embedding unsafe.
const { Node } = Type.Script(`
type Node = {
id: string
nodes: Node[]
}
`)
// Unsafe Embedding
const Container = Type.Object({ node: Node })
// const Container = {
// type: 'object',
// required: [ 'node' ],
// properties: {
// node: {
// '$defs': {
// Node: {
// type: 'object',
// required: [ 'id', 'nodes' ],
// properties: {
// id: { type: 'string' },
// nodes: { type: 'array', items: { '$ref': 'Node' } }
// },
// '$id': 'Node'
// }
// },
// '$ref': 'Node'
// }
// }
// }Safe
If the Container type is declared in the same multi-type declaration as Node, TypeBox can reason about the relationship between them. In the following example, Node is recursive, which implicitly makes Container a Cyclic as well.
const { Container } = Type.Script(`
type Node = {
id: string
nodes: Node[]
}
// Safe
type Container = {
node: Node
}
`)
// const Container = {
// '$defs': {
// Node: {
// type: 'object',
// required: [ 'id', 'nodes' ],
// properties: {
// id: { type: 'string' },
// nodes: { type: 'array', items: { '$ref': 'Node' } }
// },
// '$id': 'Node'
// },
// Container: {
// type: 'object',
// required: [ 'node' ],
// properties: { node: { '$ref': 'Node' } },
// '$id': 'Container'
// }
// },
// '$ref': 'Container'
// }Recommendation
If you need to use Cyclic types manually to express recursion, the Cyclic type should always be the outermost type, and it should contain definitions for every type it depends on or references. This keeps the schema self-contained and avoids the embedding problems described above. In the following example, Expression is the root definition. BinaryExpression refers back to Expression, which makes the type recursive, and the literal and operator types are included as definitions within the same Cyclic.
import Type from 'typebox'
type Expression = Type.Static<typeof Expression>
// Include definitions for every type required by this Cyclic.
const Expression = Type.Cyclic({
BooleanLiteral: Type.Object({
type: Type.Literal('BooleanLiteral'),
value: Type.Boolean()
}),
NumberLiteral: Type.Object({
type: Type.Literal('NumberLiteral'),
value: Type.Number()
}),
Literal: Type.Union([
Type.Ref('BooleanLiteral'),
Type.Ref('NumberLiteral'),
]),
Operator: Type.Union([
Type.Literal('+'),
Type.Literal('-'),
Type.Literal('*'),
Type.Literal('/'),
]),
BinaryExpression: Type.Object({
type: Type.Literal('BinaryExpression'),
operator: Type.Ref('Operator'),
left: Type.Ref('Expression'),
right: Type.Ref('Expression'),
}),
Expression: Type.Union([
Type.Ref('Literal'),
Type.Ref('BinaryExpression'),
]),
}, 'Expression')Design Website Docs Type Decode (`design/website/docs/type/decode.md`)
Type.Decode
The Decode function applies a uni-directional decoding transform to a type.
Example
The following applies a Decode callback that converts a number to a Hex string
const Hex = Type.Decode(Type.Number(), // const T = {
value => value.toString(16).toUpperCase() // type: 'number',
) // '~codec': {
// decode: value => value.toString(16).toUpperCase() ,
// encode: value => { throw Error('not implemented') },
// }
// }
// Use Value.Decode() to run Decode callbacks.
const D = Value.Decode(Hex, 12345678) // const D = 'BC614E'
const E = Value.Encode(Hex, D) // throw Error('not implemented')Design Website Docs Type Dependent (`design/website/docs/type/dependent.md`)
Type.Dependent
Creates a Dependent type.
⚠️ This type is an experimental syntax extension used to express dependent conditional type semantics via JSON Schema
if/then/else. TypeScript doesn't currently provide a means to express the semantics of this type, but may in the future. Users ofDependentshould therefore be mindful that if TypeScript introduces dependent types in the future, TypeBox may need to amend its implementation in line with TypeScript.
Example
Example usage is shown below.
const T = Type.Dependent([ // const T = {
Type.Number(), // if: { type: 'number' },
Type.Literal(1), // then: { type: 'number', const: 1 },
Type.String() // else: { type: 'string' }
]) // }
type T = Static<typeof T> // type T = 1 | stringSyntax
This type is an IR target for the following syntax.
type T = if number then 1 else stringLowering
As Dependent typing is not a feature of TypeScript, TypeBox uses the following lowering expression for type inference.
type Dependent<If, Then, Else> = (If & Then) | Exclude<Else, If>Where immediate inference is resolved via the following.
// type T = if number then 1 else string
// Dependent<number, 1, string>
// = (number & 1) | Exclude<string, number>
// = (1) | Exclude<string, number> -- intersection
// = (1) | (string) -- negation
type T = 1 | string // resultSome further examples:
type A = Dependent<number, 1, string> // 1 | string
type B = Dependent<number, 1, never> // 1
type C = Dependent<number, 1, unknown> // unknownGuard
Use the IsDependent function to guard values of this type.
Value.IsDependent(value) // value is TDependentDesign Website Docs Type Encode (`design/website/docs/type/encode.md`)
Type.Encode
The Encode function applies a uni-directional encoding transform to a type.
Example
The following applies an Encode callback.
⚠️ Encode callbacks will receive a value of type
unknown. This is because TypeBox cannot statically derive the Decoded state, only the Encoded state as given by the schema. Applications should apply appropriate runtime checks local to the callback and throw if receiving invalid values.
const T = Type.Encode(Type.Number(), // const T = {
(value: unknown) => value === 'hello' // type: 'number',
? 1 // '~codec': {
: 0 // decode: value => { throw Error('not implemented') },
) // encode: value => 0
// }
// }
// Use Value.Encode() to run Encode callbacks.
const D = Value.Decode(T, 12345) // throw Error('not implemented')
const E = Value.Encode(T, 'hello') // const E = 1Design Website Docs Type Enum (`design/website/docs/type/enum.md`)
Type.Enum
Creates an Enum type.
Example
Example usage is shown below.
const T = Type.Enum(['A', 'B', 'C']) // const T = {
// enum: ['A', 'B', 'C']
// }
type T = Static<typeof T> // type T = 'A' | 'B' | 'C'Guard
Use the IsEnum function to guard values of this type.
Type.IsEnum(value) // value is TEnumDesign Website Docs Type Evaluate (`design/website/docs/type/evaluate.md`)
Type.Evaluate
The Evaluate function will evaluate logical type expressions and return the result.
Example
Example usage is shown below.
const T = Type.Intersect([
Type.Object({ x: Type.Number() }),
Type.Union([
Type.Object({ y: Type.Number() }),
Type.Object({ z: Type.Number() })
])
])
const S = Type.Evaluate(T) // const S: TUnion<[
// TObject<{
// x: TNumber,
// y: TNumber
// }>,
// TObject<{
// x: TNumber,
// z: TNumber
// }>,
// ]>Remarks
The Evaluate function transforms logical type expressions into normalized forms using set-based evaluation rules. Evaluation is applied to both Union and Intersect types where Union evaluation yields the broadest disjoint types within a set while Intersect yields the narrowest.
Union
Union evaluation yields the broadest variant.
const T = Type.Union([Type.Literal(1), Type.Number()])
const S = Type.Evaluate(T) // const S = { type: 'number' }Intersect
Intersect evaluation yields the narrowest constituent
const T = Type.Intersect([Type.Literal(1), Type.Number()])
const S = Type.Evaluate(T) // const S = { const: 1 }Design Website Docs Type Exclude (`design/website/docs/type/exclude.md`)
Type.Exclude
The Exclude function will exclude types from Left that extend Right.
Example
Example usage is shown below.
const L = Type.Union([
Type.Literal('hello'),
Type.Literal('world'),
Type.Literal(1),
Type.Literal(2)
])
const R = Type.String()
const S = Type.Exclude(L, R) // const S: TUnion<[
// TLiteral<1>,
// TLiteral<2>
// ]>Design Website Docs Type Extract (`design/website/docs/type/extract.md`)
Type.Extract
The Extract function will extract types from Left that extend Right.
Example
Example usage is shown below.
const L = Type.Union([
Type.Literal('hello'),
Type.Literal('world'),
Type.Literal(1),
Type.Literal(2)
])
const R = Type.String()
const S = Type.Extract(L, R) // const S: TUnion<[
// TLiteral<'hello'>,
// TLiteral<'world'>
// ]>Design Website Docs Type Function (`design/website/docs/type/function.md`)
Type.Function
Creates a Function type.
⚠️ This type is used for interface definitions and cannot be validated.
Example
Example usage is shown below.
const T = Type.Function([ // const T = {
Type.String(), // type: 'function'
Type.Boolean() // parameters: [
], Type.Object({ // { type: 'string' },
x: Type.Number() // { type: 'boolean' }
})) // ],
// returnType: {
// type: 'object',
// required: ['x'],
// properties: {
// x: { type: 'number' }
// }
// }
// }
type T = Static<typeof T> // type T = (
// args_0: string,
// args_1: boolean
// ) => {
// x: number
// }Guard
Use the IsFunction function to guard values of this type.
Type.IsFunction(value) // value is TFunctionDesign Website Docs Type Generic (`design/website/docs/type/generic.md`)
Type.Generic
Creates a Generic type. Generic types can be instantiated with Call.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const G = Type.Generic([Type.Parameter('T')], // const G = {
Type.Array(Type.Ref('T'))) // type: 'generic',
// parameters: [{
// name: 'T',
// extends: {},
// equals: {}
// }],
// expression: {
// type: 'array',
// items: { '$ref': 'T' }
// }
// }
const S = Type.Call(G, [Type.Number()]) // const S: TArray<TNumber>Guard
Use the IsGeneric function to guard values of this type.
Type.IsGeneric(value) // value is TGenericDesign Website Docs Type Identifier (`design/website/docs/type/identifier.md`)
Type.Identifier
Creates a named Identifier.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const T = Type.Identifier('A') // const T = {
// type: 'identifier',
// name: 'A'
// }Guard
Use the IsIdentifier function to guard values of this type.
Type.IsIdentifier(value) // value is TIdentifierDesign Website Docs Type Immutable (`design/website/docs/type/immutable.md`)
Type.Immutable
The Immutable function applies an ~immutable modifier to an Array or Tuple and is used to infer readonly T[] for these types. This modifier is used for type inference and composition only. It has no effect on validation.
Example
Example usage for an Array is shown below.
const T = Type.Immutable( // const T = {
Type.Array(Type.Number()) // type: 'array',
) // items: { type: 'number' },
// '~immutable': true
// }
type T = Static<typeof T> // type T = readonly number[]The following example applies it to a Tuple.
const T = Type.Immutable( // const T = {
Type.Tuple([Type.String(), Type.Number()]) // type: 'array',
) // additionalItems: false,
// items: [
// { type: 'string' },
// { type: 'number' }
// ],
// minItems: 2,
// '~immutable': true
// }
type T = Type.Static<typeof T> // type T = readonly [string, number]Remarks
An Immutable modifier can be applied to any type, but TypeBox only uses it for type inference when applied to arrays and tuples.
Guard
Use the IsImmutable function to guard values of this type.
Type.IsImmutable(value) // value is TImmutableDesign Website Docs Type Indexed (`design/website/docs/type/indexed.md`)
Type.Index
The Index function performs an indexed access lookup on a type.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Literal(1),
y: Type.Literal(2),
z: Type.Literal(3)
})
const S = Type.Index(T, Type.Union([ // const S: TUnion<[
Type.Literal('x'), // TLiteral<1>,
Type.Literal('y') // TLiteral<2>
])) // ]>Design Website Docs Type Infer (`design/website/docs/type/infer.md`)
Type.Infer
Creates an Infer instruction to extract types in conditional type expression.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Literal(1),
y: Type.Literal(2)
})
const S = Type.Conditional(T, Type.Object({ // const S: TTuple<[
x: Type.Infer('X'), // TLiteral<1>,
y: Type.Infer('Y'), // TLiteral<2>
}), Type.Tuple([ // ]>
Type.Ref('X'),
Type.Ref('Y')
]), Type.Never())Guard
Use the IsInfer function to guard values of this type.
Type.IsInfer(value) // value is TInferDesign Website Docs Type Instance Type (`design/website/docs/type/instance-type.md`)
Type.InstanceType
Extracts the InstanceType from a Constructor type.
Example
Example usage is shown below.
const T = Type.Constructor([Type.String()], Type.Object({
x: Type.Number()
}))
const S = Type.InstanceType(T) // const S: TObject<{
// x: TNumber
// }>Design Website Docs Type Instantiate (`design/website/docs/type/instantiate.md`)
Type.Instantiate
The Instantiate function will instantiate interior references embedded within a type. This function accepts a context object as the first argument which is used to source referenced types.
Example
The following instantiates embedded Ref types.
const X = Type.Literal(1)
const Y = Type.Literal(2)
const Z = Type.Literal(3)
const T = Type.Object({
x: Type.Ref('X'),
y: Type.Ref('Y'),
z: Type.Ref('Z'),
})
const S = Type.Instantiate({ X, Y, Z }, T) // const S: TObject<{
// x: TLiteral<1>,
// y: TLiteral<2>,
// z: TLiteral<3>
// }>Design Website Docs Type Integer (`design/website/docs/type/integer.md`)
Type.Integer
Creates an Integer type.
Example
Example usage is shown below.
const T = Type.Integer() // const T = {
// type: 'integer'
// }
type T = Static<typeof T> // type T = numberGuard
Use the IsInteger function to guard values of this type.
Type.IsInteger(value) // value is TIntegerOptions
export interface TNumberOptions extends TSchemaOptions {
/**
* Specifies an exclusive upper limit for the number (number must be less than this value).
*/
exclusiveMaximum?: number | bigint
/**
* Specifies an exclusive lower limit for the number (number must be greater than this value).
*/
exclusiveMinimum?: number | bigint
/**
* Specifies an inclusive upper limit for the number (number must be less than or equal to this value).
*/
maximum?: number | bigint
/**
* Specifies an inclusive lower limit for the number (number must be greater than or equal to this value).
*/
minimum?: number | bigint
/**
* Specifies that the number must be a multiple of this value.
*/
multipleOf?: number
}Remarks
TypeBox models Integer as a narrower form of Number. All integers are numbers, but not all numbers are integers, so Integer is treated as a subset of number within conditional type expressions. This distinction aligns with JSON Schema, which defines Integer as a baseline type, even though TypeScript does not differentiate integers from numbers.
Integer is a subset of Number: true
Number is a subset of Integer: falseconst A = Type.Conditional( // const A = { const: true }
Type.Integer(),
Type.Number(),
Type.Literal(true),
Type.Literal(false)
)
const B = Type.Conditional( // const B = { const: false }
Type.Number(),
Type.Integer(),
Type.Literal(true),
Type.Literal(false)
)Design Website Docs Type Interface (`design/website/docs/type/interface.md`)
Type.Interface
The Interface function creates an Object with Heritage.
Example
Example usage is shown below.
const A = Type.Interface([], { // const A: TObject<{
a: Type.Number() // a: TNumber
}) // }>
const B = Type.Interface([A], { // const B: TObject<{
b: Type.Number() // a: TNumber,
}) // b: TNumber
// }Design Website Docs Type Intersect (`design/website/docs/type/intersect.md`)
Type.Intersect
Creates an Intersect type.
Example
Example usage is shown below.
const T = Type.Intersect([ // const T = {
Type.Object({ x: Type.Number() }), // allOf: [{
Type.Object({ y: Type.Number() }), // type: 'object',
]) // required: ['x'],
// properties: {
// x: { type: 'number' }
// }
// }, {
// type: 'object',
// required: ['y'],
// properties: {
// y: { type: 'number' }
// }
// }]
// }
type T = Static<typeof T> // type T = {
// x: number
// } & {
// y: number
// }Guard
Use the IsIntersect function to guard values of this type.
Type.IsIntersect(value) // value is TIntersectOptions
export interface TIntersectOptions extends TSchemaOptions {
/**
* A schema to apply to any properties in the object that were not validated
* by other keywords like `properties`, `patternProperties`, or `additionalProperties`.
* If `false`, no additional properties are allowed.
*/
unevaluatedProperties?: TSchema | boolean
}Design Website Docs Type Key Of (`design/website/docs/type/key-of.md`)
Type.KeyOf
Extracts Keys from an Object or Tuple.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
const S = Type.KeyOf(T) // const S: TUnion<[
// TLiteral<'x'>,
// TLiteral<'y'>,
// TLiteral<'z'>
// ]>Design Website Docs Type Literal (`design/website/docs/type/literal.md`)
Type.Literal
Creates a Literal type. Supported values are BigInt, Boolean, Number and String.
Example
Example usage is shown below.
const A = Type.Literal(1n) // const A = {
// type: 'bigint',
// const: 1n
// }
const B = Type.Literal(true) // const B = {
// type: 'boolean',
// const: true
// }
const C = Type.Literal(32) // const C = {
// type: 'number',
// const: 32
// }
const D = Type.Literal('hello') // const D = {
// type: 'string',
// const: 'hello'
// }Guard
Use the IsLiteral function to guard values of this type.
Type.IsLiteral(value) // value is TLiteral<TLiteralValue>Design Website Docs Type Lowercase (`design/website/docs/type/lowercase.md`)
Type.Lowercase
The Lowercase function will lowercase string literals.
Example
Example usage is shown below.
const T = Type.Literal('HELLO')
const S = Type.Lowercase(T) // const S: TLiteral<'hello'>Design Website Docs Type Mapped (`design/website/docs/type/mapped.md`)
Type.Mapped
Applies a Mapped operation to a type.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
// type S = {
// [K in keyof T]: T[K] | null
// }
const S = Type.Mapped( // const S: TObject<{
Type.Identifier('K'), // x: TUnion<[TNumber, TNull]>,
Type.KeyOf(T), // y: TUnion<[TNumber, TNull]>,
Type.Ref('K'), // z: TUnion<[TNumber, TNull]>,
Type.Union([ // }>
Type.Index(T, Type.Ref('K')),
Type.Null()
])
)Design Website Docs Type Module (`design/website/docs/type/module.md`)
Type.Module
The Module function is an advanced composition system for referential types. It performs several normalization passes, including reference inlining, cyclic type resolution, and dead code elimination for unused definitions. Conceptually, Module mirrors how TypeScript handles type references within the context of a TypeScript module.
Referencing
Module is written in support of order-independent type referencing. Consider the following, where type A references type B before it is defined.
type A = 1 | B // type A = 1 | 2
type B = 2 // type B = 2Attempting the same in JavaScript results in an Access before initialization error
const A = Type.Union([Type.Literal(1), B]) // Error: Cannot access 'B' before initialization
const B = Type.Literal(2)Module offers a scoping mechanism that facilitates order independent referencing.
const M = Type.Module({
A: Type.Union([
Type.Literal(1),
Type.Ref('B') // Referenced before definition.
]),
B: Type.Literal(2)
})
M.A // const A: TUnion<TLiteral<1>, TLiteral<2>>
M.B // const B: TLiteral<2>Inline
The Module function will automatically inline referenced types. Inlining means the referenced type is cloned directly into the referring type, so the final result is a fully self-contained type without external dependencies.
const { A, B, C } = Type.Module({ // const A: TNumber
A: Type.Number(), //
B: Type.String(), // const B: TString
C: Type.Object({ //
a: Type.Ref('A'), // const C: TObject<{
b: Type.Ref('B') // a: TNumber, // <-- inlined
}) // b: TString // <-- inlined
}) // }>Cyclic
The Module function will automatically detect self-referential types and transform them into instances of TCyclic.
const { A } = Type.Module({ // const A: TCyclic<{
A: Type.Object({ // A: TObject<{
b: Type.Ref('B') // b: TRef<'B'>,
}), // }>,
B: Type.Object({ // B: TObject<{
a: Type.Ref('A') // a: TRef<'A'>
}) // }>
}) // }, 'A'>Dead Code Elimination
Module also performs dead code elimination, ensuring that each definition only includes the types required for itself. In the following example, the C definition is present, but since A and B do not reference it, C is excluded from their referential set.
const { A } = Type.Module({ // const A: TCyclic<{
A: Type.Object({ // A: TObject<{
b: Type.Ref('B') // b: TRef<'B'>,
}), // }>,
B: Type.Object({ // B: TObject<{
a: Type.Ref('A') // a: TRef<'A'>
}), // }>
C: Type.String() // }, 'A'>
})Design Website Docs Type Never (`design/website/docs/type/never.md`)
Type.Never
Creates a Never type.
Example
Example usage is shown below.
const T = Type.Never() // const T = {
// not: {}
// }
type T = Static<typeof T> // type T = neverGuard
Use the IsNever function to guard values of this type.
Type.IsNever(value) // value is TNeverDesign Website Docs Type Non Nullable (`design/website/docs/type/non-nullable.md`)
Type.NonNullable
The NonNullable function will discard variants of Undefined and Null from a Union type.
Example
Example usage is shown below.
const T = Type.Union([Type.String(), Type.Undefined(), Type.Null()])
const S = Type.NonNullable(T) // const S: TStringDesign Website Docs Type Null (`design/website/docs/type/null.md`)
Type.Null
Creates a Null type.
Example
Example usage is shown below.
const T = Type.Null() // const T = { type: 'null' }
type T = Static<typeof T> // type T = nullGuard
Use the IsNull function to guard values of this type.
Type.IsNull(value) // value is TNullDesign Website Docs Type Number (`design/website/docs/type/number.md`)
Type.Number
Creates a Number type.
Example
Example usage is shown below.
const T = Type.Number() // const T = {
// type: 'number'
// }
type T = Static<typeof T> // type T = numberGuard
Use the IsNumber function to guard values of this type.
Type.IsNumber(value) // value is TNumberOptions
export interface TNumberOptions extends TSchemaOptions {
/**
* Specifies an exclusive upper limit for the number (number must be less than this value).
*/
exclusiveMaximum?: number | bigint
/**
* Specifies an exclusive lower limit for the number (number must be greater than this value).
*/
exclusiveMinimum?: number | bigint
/**
* Specifies an inclusive upper limit for the number (number must be less than or equal to this value).
*/
maximum?: number | bigint
/**
* Specifies an inclusive lower limit for the number (number must be greater than or equal to this value).
*/
minimum?: number | bigint
/**
* Specifies that the number must be a multiple of this value.
*/
multipleOf?: number
}Design Website Docs Type Object (`design/website/docs/type/object.md`)
Type.Object
Creates an Object type.
Example
Example usage is shown below.
const T = Type.Object({ // const T = {
x: Type.Number(), // type: 'object',
y: Type.Number(), // required: ['x', 'y', 'z'],
z: Type.Number() // properties: {
}) // x: { type: 'number' },
// y: { type: 'number' },
// z: { type: 'number' }
// }
// }
type T = Static<typeof T> // type T = {
// x: number,
// y: number,
// z: number
// }Guard
Use the IsObject function to guard values of this type.
Type.IsObject(value) // value is TObjectOptions
The following options are available for Object
export interface TObjectOptions extends TSchemaOptions {
/**
* Defines whether additional properties are allowed beyond those explicitly defined in `properties`.
*/
additionalProperties?: TSchema | boolean
/**
* The minimum number of properties required in the object.
*/
minProperties?: number
/**
* The maximum number of properties allowed in the object.
*/
maxProperties?: number
/**
* Defines conditional requirements for properties.
*/
dependencies?: Record<string, boolean | TSchema | string[]>
/**
* Specifies properties that *must* be present if a given property is present.
*/
dependentRequired?: Record<string, string[]>
/**
* Defines schemas that apply if a specific property is present.
*/
dependentSchemas?: Record<string, TSchema>
/**
* Maps regular expressions to schemas that matching properties must validate against.
*/
patternProperties?: Record<string, TSchema>
/**
* A schema that all property names within the object must validate against.
*/
propertyNames?: TSchema
}Design Website Docs Type Omit (`design/website/docs/type/omit.md`)
Type.Omit
Omits keys from the given Object type.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
const S = Type.Omit(T, Type.Union([ // const S: TObject<{
Type.Literal('z') // x: TNumber,
])) // y: TNumber
// }>Design Website Docs Type Optional (`design/website/docs/type/optional.md`)
Type.Optional
The Optional function applies an optional ? modifier to a type.
Example
Example usage is shown below.
const T = Type.Object({ // const T = {
x: Type.Optional(Type.Number()), // type: 'object',
y: Type.Optional(Type.Number()), // required: ['z'],
z: Type.Number() // properties: {
}) // x: { type: 'number', '~optional': true },
// y: { type: 'number', '~optional': true },
// z: { type: 'number' }
// }
// }
type T = Static<typeof T> // type T = {
// x?: number,
// y?: number,
// z: number
// }Guard
Use the IsOptional function to guard values of this type.
const checked = Type.IsOptional(value) // value is TOptionalDesign Website Docs Type Options (`design/website/docs/type/options.md`)
Type.Options
Options can be passed on the last argument of any given type.
Example
Example usage is shown below.
const T = Type.Number({ // const T = {
minimum: 10, // type: 'number',
maximum: 100 // minimum: 10,
}) // maximum: 100
// }
// const T: TNumberDesign Website Docs Type Parameter (`design/website/docs/type/parameter.md`)
Type.Parameter
Creates a Generic Parameter type.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const T = Type.Parameter('A', // const T = {
Type.Number(), // type: 'parameter',
Type.Literal(1) // name: 'A',
) // extends: { type: 'number' },
// equals: { const: 1 }
// }
type T = Static<typeof T> // type T = unknownGuard
Use the IsParameter function to guard values of this type.
Type.IsParameter(value) // value is TParameterDesign Website Docs Type Parameters (`design/website/docs/type/parameters.md`)
Type.Parameters
The Parameters function will extract Parameters from a Function type.
Example
Example usage is shown below.
const T = Type.Function([Type.String(), Type.Number()], Type.Object({}))
const S = Type.Parameters(T) // const S: TTuple<[
// TString,
// TNumber
// ]>Design Website Docs Type Partial (`design/website/docs/type/partial.md`)
Type.Partial
This type is an alias for the Partial<T> TypeScript utility type. It makes all properties of an Object optional.
Example
Example usage is shown below.
const T = Type.Object({ // const T: TObject<{
x: Type.Number(), // x: TNumber,
y: Type.Number(), // y: TNumber,
z: Type.Number() // z: TNumber
}) // }>
const S = Type.Partial(T) // const S: TObject<{
// x: TOptional<TNumber>,
// y: TOptional<TNumber>,
// z: TOptional<TNumber>
// }>Design Website Docs Type Pick (`design/website/docs/type/pick.md`)
Type.Pick
Picks property keys from the given Object type.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number(),
y: Type.Number(),
z: Type.Number()
})
const S = Type.Pick(T, Type.Union([ // const S: TObject<{
Type.Literal('x') // x: TNumber,
Type.Literal('y') // y: TNumber
])) // }>Design Website Docs Type Readonly Object (`design/website/docs/type/readonly-object.md`)
Type.ReadonlyObject
This type is an alias for TypeScript's Readonly<T> utility type. It makes all properties of a TObject readonly, or marks a TArray or TTuple as immutable (readonly T[]).
Example
When applied to a TObject, each property is marked as TReadonly<T>.
const T = Type.Object({ // const T = TObject<{
x: Type.Number(), // x: TNumber,
y: Type.Number(), // y: TNumber,
z: Type.Number() // z: TNumber,
}) // }>
const S = Type.ReadonlyObject(T) // const S: TObject<{
// x: TReadonly<TNumber>,
// y: TReadonly<TNumber>,
// z: TReadonly<TNumber>
// }>When applied to an Array or Tuple, the type is marked as TImmutable<T>
const T = Type.Tuple([ // const T = TImmutable<TTuple<[
Type.Number(), // TNumber,
Type.String(), // TString
]) // ]>>
const S = Type.ReadonlyObject(T) // const S: TImmutable<TTuple<[
// TNumber,
// TString
// ]>>
type S = Type.Static<typeof S> // type S = readonly [number, string]Design Website Docs Type Readonly (`design/website/docs/type/readonly.md`)
Type.Readonly
The Readonly function applies a readonly modifier to an object property. This modifier is used for type inference and composition only. It has no effect on validation.
Example
Example usage is shown below.
const T = Type.Object({ // const T = {
x: Type.Readonly(Type.Number()), // type: 'object',
y: Type.Readonly(Type.Number()), // required: ['x', 'y', 'z'],
z: Type.Number() // properties: {
}) // x: { type: 'number', '~readonly': true },
// y: { type: 'number', '~readonly': true },
// z: { type: 'number' }
// }
// }
type T = Static<typeof T> // type T = {
// readonly x: number,
// readonly y: number,
// z: number
// }Guard
Use the IsReadonly function to guard values of this type.
Type.IsReadonly(value) // value is TReadonlyDesign Website Docs Type Record (`design/website/docs/type/record.md`)
Type.Record
Creates a Record type.
Example
Example usage is shown below.
const T = Type.Record(Type.String(), Type.Number()) // const T = {
// type: 'object',
// patternProperties: {
// "^.*$": {
// type: 'number'
// }
// }
// }
type T = Static<typeof T> // type T = {
// [x: string]: number
// }Guard
Use the IsRecord function to guard values of this type.
Type.IsRecord(value) // value is TRecord<string, TSchema>Design Website Docs Type Ref (`design/website/docs/type/ref.md`)
Type.Ref
Creates a Ref type.
Example
Example usage is shown below.
const T = Type.Ref('A') // const T = {
// $ref: 'A'
// }
type T = Static<typeof T> // type T = unknownGuard
Use the IsRef function to guard values of this type.
Type.IsRef(value) // value is TRefDesign Website Docs Type Refine (`design/website/docs/type/refine.md`)
Type.Refine
The Refine function applies explicit validation logic to a type. Unlike structural type checks, Refine allows you to express constraints that cannot be captured by JSON Schema alone, such as cross-property checks, mathematical properties, or domain-specific business rules.
Example
The following creates a Refine type that validates a number is prime.
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Type Required (`design/website/docs/type/required.md`)
Type.Required
Makes all properties of an Object required.
Example
Example usage is shown below.
const T = Type.Object({ // const T = {
x: Type.Optional(Type.Number()), // type: 'object',
y: Type.Optional(Type.Number()), // properties: {
z: Type.Optional(Type.Number()) // x: { type: 'number' },
}) // y: { type: 'number' },
// z: { type: 'number' }
// }
// }
const S = Type.Required(T) // const S: TObject<{
// x: TNumber,
// y: TNumber,
// z: TNumber
// }>Design Website Docs Type Rest (`design/website/docs/type/rest.md`)
Type.Rest
Creates a Rest type.
⚠️ This function is a Script evaluation action.
Example
Example usage is shown below.
const T = Type.Rest(Type.Tuple([ // const T = {
Type.Literal(1), // type: "rest",
Type.Literal(2) // items: {
])) // type: "array",
// additionalItems: false,
// items: [
// { const: 1 },
// { const: 2 }
// ],
// minItems: 2
// }
// }
type T = Static<typeof T> // type T = [1, 2][]Guard
Use the IsRest function to guard values of this type.
Type.IsRest(value) // value is TRestDesign Website Docs Type Return Type (`design/website/docs/type/return-type.md`)
Type.ReturnType
Extracts the ReturnType from a Function.
Example
Example usage is shown below.
const T = Type.Function([Type.String()], Type.Object({
x: Type.Number()
}))
const S = Type.ReturnType(T) // const S: TObject<{
// x: TNumber
// }>Design Website Docs Type Static (`design/website/docs/type/static.md`)
Type.Static
The Static type infers a TypeScript type from a TypeBox type or JSON Schema.
Example
const T = Type.Number()
type T = Static<typeof T> // type T = numberRemarks
The Static type can also infer a TypeScript type from raw JSON Schema.
JSON Schema
const T = { oneOf: [{ const: 1 }, { const: 2 }] } as const
type T = Static<typeof T> // type T = 1 | 2Design Website Docs Type String (`design/website/docs/type/string.md`)
Type.String
Creates a String type.
Example
Example usage is shown below.
const T = Type.String() // const T = {
// type: 'string'
// }
type T = Static<typeof T> // type T = stringGuard
Use the IsString function to guard values of this type.
Type.IsString(value) // value is TStringOptions
The following options are available for String
export interface TStringOptions extends TSchemaOptions {
/**
* A string format such as 'email', 'uuid' or other registered format.
*/
format?: TFormat
/**
* Specifies the minimum number of characters allowed in the string.
* Must be a non-negative integer.
*/
minLength?: number
/**
* Specifies the maximum number of characters allowed in the string.
* Must be a non-negative integer.
*/
maxLength?: number
/**
* Specifies a regular expression pattern that the string value must match.
* Can be provided as a string (ECMA-262 regex syntax) or a `RegExp` object.
*/
pattern?: string | RegExp
}Design Website Docs Type Symbol (`design/website/docs/type/symbol.md`)
Type.Symbol
Creates a Symbol type.
⚠️ This type cannot be expressed in standard JSON Schema. Do not use it if publishing types for other languages to consume.
Example
Example usage is shown below.
const T = Type.Symbol() // const T = {
// type: 'symbol'
// }
type T = Static<typeof T> // type T = symbolGuard
Use the IsSymbol function to guard values of this type.
Type.IsSymbol(value) // value is TSymbolDesign Website Docs Type Template Literal (`design/website/docs/type/template-literal.md`)
Type.TemplateLiteral
Creates a TemplateLiteral type.
Example
Example usage is shown below.
const T = Type.TemplateLiteral('A${"B"|"C"}') // const T = {
// type: 'string',
// pattern: '^A(B|C)$'
// }
type T = Static<typeof T> // type T = 'AB' | 'AC'Guard
Use the IsTemplateLiteral function to guard values of this type.
Type.IsTemplateLiteral(value) // value is TTemplateLiteralDesign Website Docs Type This (`design/website/docs/type/this.md`)
Type.This
Creates a This type.
⚠️ The
Thistype is supported for top-level Object and Interface types only. The type is represented as a{ $ref: '#' }reference that always points to the root of the schema. TypeBox does not transform#references when embedding Objects within other Objects, so care should be taken when using this type.
Example
Example usage is shown below.
const T = Type.Object({ // const T = {
items: Type.Array(Type.This()) // type: 'object',
}) // required: ['items'],
// properties: {
// items: { $ref: '#' }
// }
// }
type T = Static<typeof T> // type T = objectGuard
Use the IsThis function to guard values of this type.
Type.IsThis(value) // value is TThisDesign Website Docs Type Tuple (`design/website/docs/type/tuple.md`)
Type.Tuple
Creates a Tuple type.
Example
Example usage is shown below.
const T = Type.Tuple([ // const T = {
Type.String(), // type: 'array',
Type.Number(), // additionalItems: false,
]) // minItems: 2,
// items: [
// { type: 'string' },
// { type: 'number' },
// ]
// }
type T = Static<typeof T> // type T = [string, number]Guard
Use the IsTuple function to guard values of this type.
Type.IsTuple(value) // value is TTupleDesign Website Docs Type Uncapitalize (`design/website/docs/type/uncapitalize.md`)
Type.Uncapitalize
The Uncapitalize function will uncapitalize string literals.
Example
Example usage is shown below.
const T = Type.Literal('HELLO')
const S = Type.Uncapitalize(T) // const S: TLiteral<'hELLO'>Design Website Docs Type Undefined (`design/website/docs/type/undefined.md`)
Type.Undefined
Creates an Undefined type.
⚠️ This type cannot be expressed in standard JSON Schema. Do not use it if publishing types for other languages to consume.
Example
Example usage is shown below.
const T = Type.Undefined() // const T = {
// type: 'undefined'
// }
type T = Static<typeof T> // type T = undefinedGuard
Use the IsUndefined function to guard values of this type.
Type.IsUndefined(value) // value is TUndefinedDesign Website Docs Type Union (`design/website/docs/type/union.md`)
Type.Union
Creates a Union type.
Example
Example usage is shown below.
const T = Type.Union([ // const T = {
Type.String(), // anyOf: [
Type.Number() // { type: 'string' },
]) // { type: 'number' }
// ]
// }
type T = Static<typeof T> // type T = string | numberGuard
Use the IsUnion function to guard values of this type.
Type.IsUnion(value) // value is TUnionDesign Website Docs Type Unknown (`design/website/docs/type/unknown.md`)
Type.Unknown
Creates an Unknown type.
Example
Example usage is shown below.
const T = Type.Unknown() // const T = { }
type T = Static<typeof T> // type T = unknownGuard
Use the IsUnknown function to guard values of this type.
Type.IsUnknown(value) // value is TUnknownDesign Website Docs Type Unsafe (`design/website/docs/type/unsafe.md`)
Type.Unsafe
The Unsafe type is used to create user-defined schemas with user-defined inference rules. The type is named so because it is possible to create schemas that are mismatched to the inferred type. The Unsafe type offers an escape hatch for scenarios when you need schemas not generated by TypeBox.
Example
The following creates an Unsafe number schema that infers as string.
const T = Type.Unsafe<string>({ type: 'number' }) // const T = { type: 'number' }
type T = Static<typeof T> // type T = stringDesign Website Docs Type Uppercase (`design/website/docs/type/uppercase.md`)
Type.Uppercase
The Uppercase function will uppercase string literals.
Example
Example usage is shown below.
const T = Type.Literal('hello')
const S = Type.Uppercase(T) // const S: TLiteral<'HELLO'>Design Website Docs Type Void (`design/website/docs/type/void.md`)
Type.Void
Creates a Void type.
⚠️ This type cannot be expressed in standard JSON Schema. Do not use it if publishing types for other languages to consume.
Example
Example usage is shown below.
const T = Type.Void() // const T = { type: 'void' }
type T = Static<typeof T> // type T = voidGuard
Use the IsVoid function to guard values of this type.
Type.IsVoid(value) // value is TVoidDesign Website Docs Type With (`design/website/docs/type/with.md`)
Type.With
An action that augments a type with additional constraints and annotations. This action is similar to options, but where the option data is statically introspectable on the schema.
⚠️ This action is used to express the Script
withkeyword.
Syntax
This type is an IR target for the following syntax.
type T = string with { format: 'email' }Example
Example usage is shown below.
const T = Type.With(Type.Number(), { // const T = {
minimum: 10, // type: 'number',
maximum: 100 // minimum: 10,
}) // maximum: 100
// }
// const T: TWith<TNumber, {
// minimum: number;
// maximum: number;
// }>Design Website Docs Value Assert (`design/website/docs/value/assert.md`)
Value.Assert
The Assert function throws an AssertError if the value does not match the type.
Example
Example usage is shown below.
const T = Type.Number()
Value.Assert(T, 42) // OK
Value.Assert(T, 'not a number') // throws AssertErrorDesign Website Docs Value Check (`design/website/docs/value/check.md`)
Value.Check
The Check function returns true if the value matches the type.
Example
Example usage is shown below.
const T = Type.Number()
const A = Value.Check(T, 42) // const A = true
const B = Value.Check(T, 'not-a-number') // const B = falseDesign Website Docs Value Clean (`design/website/docs/value/clean.md`)
Value.Clean
The Clean function will remove excess properties or elements from a value.
⚠️ The Clean function may return invalid data if the provided value is itself invalid. This function does not perform any checks on the value to ensure the data is correct. The function returns
unknownand therefore results should be checked before use.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number(),
y: Type.Number()
})
const R = Value.Clean(T, { x: 1, y: 2, z: 3 }) // const R = { x: 1, y: 2 }const T = Type.Tuple([
Type.Number(),
Type.Number()
])
const R = Value.Clean(T, [1, 2, 3]) // const R = [1, 2]Design Website Docs Value Clone (`design/website/docs/value/clone.md`)
Value.Clone
The Clone function will clone a value. This function is similar to structuredClone() but also clones JavaScript collections such as Map, Set, and TypedArray.
Example
Example usage is shown below.
const A = { x: 1, y: 2, z: 3 }
const B = Value.Clone(A) // const B = { x: 1, y: 2, z: 3 }Design Website Docs Value Convert (`design/website/docs/value/convert.md`)
Value.Convert
The Convert function will convert values to match the given type if a reasonable conversion is possible. If no conversion is possible, the original value is returned unchanged.
⚠️ The Convert function may return invalid data if the provided value is invalid. This function does not perform any checks on the value to ensure the data is correct. This function returns
unknownand therefore results should be checked before use.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number()
})
// ...
const A = Value.Convert(T, { x: '3.14' }) // const A = { x: 3.14 }
const B = Value.Convert(T, { x: 'not a number' }) // const B = { x: 'not a number' }Design Website Docs Value Create (`design/website/docs/value/create.md`)
Value.Create
The Create function will create an instance of the given type.
Example
Example usage is shown below.
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
// }Ambiguous Constraints
The Create function will consider an operation ambiguous if the type being created includes constraints that could produce an invalid value. For example, applying a format constraint to a String type is considered ambiguous, as the Create function cannot determine what kind of format it should generate.
const T = Type.String({
format: 'email'
})
const A = Value.Create(T) // throws CreateErrorTo fix, apply a default annotation to the type.
const T = Type.String({
format: 'email',
default: '[email protected]'
})
const A = Value.Create(T) // const A: string = '[email protected]'Design Website Docs Value Decode (`design/website/docs/value/decode.md`)
Value.Decode
The Decode function will execute Decode callbacks embedded within the provided type.
⚠️ This function may throw an error if the provided value is invalid or if a failure occurs during the decoding process. It is recommended to wrap this function in a try / catch block.
Example
Example usage is shown below.
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
// }Pipeline
The Decode function uses the following Decoder pipeline.
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
])Unsafe
The Decode function runs the full decoder pipeline to ensure Codec callbacks receive validated values. In some cases, applications may require greater control, for example, to optimize performance or integrate with functions beyond what is offered by TypeBox. For these scenarios, the Value module provides the DecodeUnsafe function, which executes Codec callbacks directly without additional processing.
⚠️ The DecodeUnsafe function returns unknown and provides no assurances the decoded value is valid. Callers must handle validation and inference manually. This is usually achieved by wrapping a pipeline in a generic function constrained by a TypeBox type.
The example below defines a reduced decoder that runs only Assert and Codec callbacks.
import { Pipeline, Assert, DecodeUnsafe } from 'typebox/value'
// CustomDecoder
const CustomDecoder = Pipeline([
(context, type, value) => { Assert(context, type, value); return value },
(context, type, value) => DecodeUnsafe(context, type, value)
])
// Type + Decode
const NumberToString = Type.Decode(Type.Number(), value => value.toString())
// Result
const Result = CustomDecoder(NumberToString, 123456) // const Result: unknown = "123456"Design Website Docs Value Default (`design/website/docs/value/default.md`)
Value.Default
The Default function automatically generates values for any missing properties or elements whose type includes a default annotation. If no such annotation exists, the function will not generate a value. This function is most commonly used in HTTP request pipelines to provide reasonable defaults for optional, user-defined properties.
⚠️ The Default function may return invalid data if the provided value is itself invalid. This function does not perform any checks on the value to ensure the data is correct. The function returns
unknownand therefore results should be checked before use.
Example
Example usage is shown below.
const Pagination = Type.Object({
skip: Type.Optional(Type.Number({ default: 0 })),
take: Type.Optional(Type.Number({ default: 10 }))
})
const A = Value.Default(Pagination, {}) // const A = { skip: 0, take: 10 }
const B = Value.Default(Pagination, { skip: 10 }) // const B = { skip: 10, take: 10 }
const C = Value.Default(Pagination, { take: 100 }) // const C = { skip: 0, take: 100 }Design Website Docs Value Diff (`design/website/docs/value/diff.md`)
Value.Diff
The Diff function computes a sequence of Edit commands to transform the Left value into the Right value. The resulting Edit commands can be passed to Patch, which executes them in sequence.
This function is used to synchronize large data structures over a network by transmitting only the Edit commands representing state changes. Applications are expected to maintain both the old and new states. The Clone function is commonly used to copy the old state into a mutable new state, and Hash can be used to compute a local hash of the state. This hash can be transmitted along with the Edit commands to verify that the applied edits produced the expected current value.
Example
Example usage is shown below.
const L = { x: 1, y: 2, z: 3 } // Left
const R = { y: 4, z: 5, w: 6 } // Right
const E = Value.Diff(L, R) // const E = [
// { type: 'update', path: '/y', value: 4 },
// { type: 'update', path: '/z', value: 5 },
// { type: 'insert', path: '/w', value: 6 },
// { type: 'delete', path: '/x' }
// ]Design Website Docs Value Encode (`design/website/docs/value/encode.md`)
Value.Encode
The Encode function will execute Encode callbacks embedded within the provided type.
⚠️ This function may throw an error if the provided value is invalid or if a failure occurs during the encoding process. It is recommended to wrap this function in a try/catch block.
Example
Example usage is shown below.
const Timestamp = Type.Codec(Type.Number())
.Decode(value => new Date(value))
.Encode(value => value.getTime())
const T = Type.Object({
date: Timestamp
})
const R = Value.Encode(T, { // const R = {
date: new Date('1970-01-01T00:00:12.345Z') // date: 12345
}) // }Pipeline
The Encode function uses the following Encoder pipeline.
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),
])Unsafe
The Encode function runs the full encoder pipeline to ensure Codec callbacks receive validated values. In some cases, applications may require greater control, for example, to optimize performance or integrate with functions beyond what is offered by TypeBox. For these scenarios, the Value module provides the EncodeUnsafe function, which executes Codec callbacks directly without additional processing.
⚠️ The EncodeUnsafe function returns unknown and provides no assurances the encoded value is valid. Callers must handle validation and inference manually. This is usually achieved by wrapping a pipeline in a generic function constrained by a TypeBox type.
The example below defines a reduced encoder that runs only Assert and Codec callbacks.
import { Pipeline, Assert, EncodeUnsafe } from 'typebox/value'
// CustomEncoder
const CustomEncoder = Pipeline([
(context, type, value) => EncodeUnsafe(context, type, value),
(context, type, value) => { Assert(context, type, value); return value },
])
// Type + Encode
const StringToNumber = Type.Encode(Type.Number(), (value: unknown) =>
typeof value === 'string'
? parseFloat(value)
: 0
)
// Encode
const Result = CustomEncoder(StringToNumber, '123456') // const Result: unknown = 123456Design Website Docs Value Equal (`design/website/docs/value/equal.md`)
Value.Equal
The Equal function performs a structural value comparison against JavaScript values.
Example
Example usage is shown below.
const R = Value.Equal( // const R = true
{ x: 1, y: 2, z: 3 },
{ x: 1, y: 2, z: 3 }
)Design Website Docs Value Errors (`design/website/docs/value/errors.md`)
Value.Errors
The Errors(...) function returns an array of gathered validation errors up to the configured maxErrors limit. If the value contains no errors, an empty array is returned.
⚠️ For performance, this function should only be called after a failed Check. The function performs an exhaustive check up to the
maxErrorssetting (the default is8). For additional performance, consider reducingmaxErrorsto1, which will terminate gathering on the first error.
Example
Example usage is shown below.
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Value Hash (`design/website/docs/value/hash.md`)
Value.Hash
The Hash function creates a structural hash of a JavaScript value. It returns a padded 64-bit hexadecimal string. Internally, this function computes an accumulated fnv1a-64 hash across all properties, elements, and embedded values of the input. It is intended to generate fast computed hash codes for arbitrary JavaScript data structures.
⚠️ Applications should not rely on this function to store persistent hashes. The hashing algorithm is specific to TypeBox and is not based on any formal specification. While the algorithm is generally considered stable, it may be replaced with a JavaScript hashing specification should one emerge. This function should only be used to compare two values.
Example
Example usage is shown below.
const A = Value.Hash({ x: 1, y: 2, z: 3 }) // const A = '0834a0916e3e4db0'
const B = Value.Hash({ x: 1, y: 4, z: 3 }) // const B = '279c16b78fba6600'Design Website Docs Value Mutate (`design/website/docs/value/mutate.md`)
Value.Mutate
The Mutate function mutates a value while preserving interior object and array references.
⚠️ The Mutate function is designed to prevent unintended actions in state-aware frameworks such as React. It updates interior non-reference values while retaining object and array references, which can be helpful when optimizing for state-aware systems.
Example
Example usage is shown below.
const Y = { z: 1 } // const Y = { z: 1 }
const X = { y: Y } // const X = { y: { z: 1 } }
const Z = { x: X } // const Z = { x: { y: { z: 1 } } }
// Mutation
Value.Mutate(Z, { x: { y: { z: 2 } } }) // Z = { x: { y: { z: 2 } } }
const A = Z.x.y.z === 2 // const A = true
const B = Z.x.y === Y // const B = true
const C = Z.x === X // const C = trueDesign Website Docs Value Parse (`design/website/docs/value/parse.md`)
Value.Parse
The Parse function validates and returns a value that conforms to a given type. If the value does not satisfy the type, a parse error is thrown.
Example
Example usage is shown below.
const R = Value.Parse(Type.String(), 'hello') // const R: string = "hello"
const E = Value.Parse(Type.String(), 12345) // throws ParseErrorCorrective Parse
TypeBox provides an optional corrective parsing mode that attempts to repair invalid values before failing. When enabled, the parser runs a pipeline consisting of Convert, Default, and Clean, then re-asserts the value after processing. This feature can be useful when parsing environment variables into target types.
⚠️ This feature can impact performance. It is not recommended for use in high throughput applications.
This feature can be enabled as follows:
import { Settings } from 'typebox/system'
// Corrective Parse: Enable
Settings.Set({ correctiveParse: true })
// Corrective Parse: Convert Value into the target type if reasonable conversion is possible.
const R = Value.Parse(Type.String(), 'hello') // const R: string = "hello"
const S = Value.Parse(Type.String(), 12345) // const S: string = "12345"
// Corrective Parse: Reset (optional)
Settings.Reset()Design Website Docs Value Patch (`design/website/docs/value/patch.md`)
Value.Patch
The Patch function applies a sequence of Edit commands to a value.
Example
Example usage is shown below.
const L = { x: 1, y: 2, z: 3 } // Left
const R = { y: 4, z: 5, w: 6 } // Right
const E = Value.Diff(L, R) // const E = [
// { type: 'update', path: '/y', value: 4 },
// { type: 'update', path: '/z', value: 5 },
// { type: 'insert', path: '/w', value: 6 },
// { type: 'delete', path: '/x' }
// ]
// Patch Left with Edits
const A = Value.Patch(L, E) // const A = { y: 4, z: 5, w: 6 }Design Website Docs Value Pipeline (`design/website/docs/value/pipeline.md`)
Value.Pipeline
Value functions are commonly used to pre-process data before running Check or Parse operations. When multiple value functions are executed in sequence, this process is called a pipeline. TypeBox provides a Pipeline utility that allows you to compose multiple Value operations into a single callable function that follows the standard Value.* signature.
Example
Example usage is shown below.
/* Detailed source-code truncated for AI context efficiency. */Design Website Docs Value Pointer (`design/website/docs/value/pointer.md`)
Value.Pointer
The Pointer namespace is an implementation of RFC 6901 JSON Pointer. It provides functions to read and write values using JSON Pointers.
Get
The Get function will return a value at the pointer or undefined.
const X = { x: 1 }
const A = Value.Pointer.Get(X, '/x') // const A = 1
const B = Value.Pointer.Get(X, '/y') // const B = undefinedSet
The Set will update a value at the given pointer. If the path does not exist it is created.
const X = { x: 1 }
Value.Pointer.Set(X, '/x', 100) // X' = { x: 100 }
Value.Pointer.Set(X, '/y', 200) // X' = { x: 100, y: 200 }Has
The Has function returns true if a value exists at the pointer.
const X = { x: 1 }
const A = Value.Pointer.Has(X, '/x') // const A = true
const B = Value.Pointer.Has(X, '/y') // const B = falseDelete
The Delete function removes a value at the given path. It does nothing if the path does not exist.
const X = { x: 1 }
Value.Pointer.Delete(X, '/x') // X' = { }
Value.Pointer.Delete(X, '/y') // X' = { } (no action)Design Website Docs Value Repair (`design/website/docs/value/repair.md`)
Value.Repair
The Repair function will repair a value to match the provided type. If the value already matches, no action is taken. This function will try to retain as much information as possible from the original value.
Example
Example usage is shown below.
const T = Type.Object({
x: Type.Number(),
y: Type.Number()
}, { additionalProperties: false }) // Tip: Use additionalProperties: false if you want
// Repair to remove excess properties. By default,
// the Repair function retain excess properties to
// avoid data loss.
// ...
const A = Value.Repair(T, null) // const A = { x: 0, y: 0 }
const B = Value.Repair(T, { x: 1 }) // const B = { x: 1, y: 0 }
const C = Value.Repair(T, { x: 1, y: 2, z: 3 }) // const C = { x: 1, y: 2 }
const D = Value.Repair(T, { x: true, y: '42' }) // const D = { x: 1, y: 42 }--- METRICS ---
- Files Extracted: 143
- Estimated Token Budget: ~48275 tokens
- Canonical Reference: https://codewiki.google/github.com/sinclairzx81/typebox