TypeBox

JSON Schema Type Builder with Static Type Resolution for TypeScript



npm version Downloads GitHub CI

Install

Npm

$ npm install @sinclair/typebox --save

Deno

import { Static, Type } from 'npm:@sinclair/typebox'

Esm

import { Static, Type } from 'https://esm.sh/@sinclair/typebox'

Example

import { Static, Type } from '@sinclair/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 = Static<typeof T>                            // type T = {
                                                     //   x: number,
                                                     //   y: number,
                                                     //   z: number
                                                     // }

Overview

TypeBox is a runtime type builder that constructs in-memory JSON Schema objects that can be statically inferred as TypeScript types. The schemas produced by this library are designed to match the static type checking rules of the TypeScript compiler. TypeBox enables one to create a unified type that can be statically checked by TypeScript and runtime asserted using standard JSON Schema validation.

This library is designed to enable JSON schema to compose with the same flexibility as TypeScript's type system. It can be used as a simple tool to build up complex schemas or integrated into REST and RPC services to help validate data received over the wire.

License MIT

Contents

Usage

The following shows general usage.

import { Static, Type } from '@sinclair/typebox'

//--------------------------------------------------------------------------------------------
//
// Let's say you have the following type ...
//
//--------------------------------------------------------------------------------------------

type T = {
  id: string,
  name: string,
  timestamp: number
}

//--------------------------------------------------------------------------------------------
//
// ... you can express this type in the following way.
//
//--------------------------------------------------------------------------------------------

const T = Type.Object({                              // const T = {
  id: Type.String(),                                 //   type: 'object',
  name: Type.String(),                               //   properties: { 
  timestamp: Type.Integer()                          //     id: { 
})                                                   //       type: 'string' 
                                                     //     },
                                                     //     name: { 
                                                     //       type: 'string' 
                                                     //     },
                                                     //     timestamp: { 
                                                     //       type: 'integer' 
                                                     //     }
                                                     //   }, 
                                                     //   required: [
                                                     //     'id',
                                                     //     'name',
                                                     //     'timestamp'
                                                     //   ]
                                                     // } 

//--------------------------------------------------------------------------------------------
//
// ... then infer back to the original static type this way.
//
//--------------------------------------------------------------------------------------------

type T = Static<typeof T>                            // type T = {
                                                     //   id: string,
                                                     //   name: string,
                                                     //   timestamp: number
                                                     // }

//--------------------------------------------------------------------------------------------
//
// ... then use the type both as JSON schema and as a TypeScript type.
//
//--------------------------------------------------------------------------------------------

import { Value } from '@sinclair/typebox/value'

function receive(value: T) {                         // ... as a Static Type

  if(Value.Check(T, value)) {                        // ... as a JSON Schema
  
    // ok...
  }
}

Types

TypeBox types are small JSON schema fragments which can compose into more complex types though function composition. Each fragment is strictly defined to match to the static type checking rules of TypeScript. TypeBox provides a Standard type set which produces standards compliant JSON schema as well as an Extended type set used to define native JavaScript constructs.

Standard Types

The following table lists the Standard TypeBox types. These types are fully compatible with the JSON Schema specification.

┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
│ TypeBoxTypeScriptJSON Schema                    │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Any()type T = anyconst T = { }                  │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Unknown()type T = unknownconst T = { }                  │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.String()type T = stringconst T = {                    │
│                                │                             │   type: 'string'               │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Number()type T = numberconst T = {                    │
│                                │                             │   type: 'number'               │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Integer()type T = numberconst T = {                    │
│                                │                             │   type: 'integer'              │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Boolean()type T = booleanconst T = {                    │
│                                │                             │   type: 'boolean'              │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Null()type T = nullconst T = {                    │
│                                │                             │    type: 'null'                │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Literal(42)type T = 42const T = {                    │
│                                │                             │    const: 42,                  │
│                                │                             │    type: 'number'              │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Array(type T = number[]const T = {                    │
│   Type.Number()                │                             │   type: 'array',               │
│ )                              │                             │   items: {                     │
│                                │                             │     type: 'number'             │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Object({type T = {const T = {                    │
│   x: Type.Number(),            │   x: number,                │   type: 'object',              │
│   y: Type.Number()             │   y: number                 │   required: ['x', 'y'],        │
│ })}                           │   properties: {                │
│                                │                             │     x: {                       │
│                                │                             │       type: 'number'           │
│                                │                             │     }, {                       │
│                                │                             │       type: 'number'           │
│                                │                             │     }                          │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Tuple([type T = [number, number]const T = {                    │
│   Type.Number(),               │                             │   type: 'array',               │
│   Type.Number()                │                             │   items: [{                    │
│ ])                             │                             │      type: 'number'            │
│                                │                             │    }, {                        │
│                                │                             │      type: 'number'            │
│                                │                             │    }],                         │
│                                │                             │    additionalItems: false,     │
│                                │                             │    minItems: 2,                │
│                                │                             │    maxItems: 2                 │
│                                │                             │ }                              │
│                                │                             │                                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ enum Foo {enum Foo {const T = {                    │
│   A,A,                        │   anyOf: [{                    │
│   BB                         │     type: 'number',            │
│ }}const: 0                   │
│                                │                             │   }, {                         │
│ const T = Type.Enum(Foo)type T = Foo                │     type: 'number',            │
│                                │                             │     const: 1                   │
│                                │                             │   }]                           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.KeyOf(type T = keyof {const T = {                    │
│   Type.Object({                │   x: number,                │   anyOf: [{                    │
│     x: Type.Number(),          │   y: number                 │     type: 'string',            │
│     y: Type.Number()}const: 'x'                 │
│   })                           │                             │   }, {                         │
│ )                              │                             │     type: 'string',            │
│                                │                             │     const: 'y'                 │
│                                │                             │   }]                           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Union([type T = string | numberconst T = {                    │
│   Type.String(),               │                             │   anyOf: [{                    │
│   Type.Number()                │                             │      type: 'string'            │
│ ])                             │                             │   }, {                         │
│                                │                             │      type: 'number'            │
│                                │                             │   }]                           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Intersect([type T = {const T = {                    │
│   Type.Object({                │   x: number                 │   allOf: [{                    │
│     x: Type.Number()} & {                       │     type: 'object',            │
│   }),                          │   y: number                 │     required: ['x'],           │
│   Type.Object({}                           │     properties: {              │
│     y: Type.Number()           │                             │       x: {                     │
│   ])                           │                             │         type: 'number'         │
│ ])                             │                             │       }                        │
│                                │                             │     }                          │
│                                │                             │   }, {                         │
│                                │                             │     type: 'object',            |
│                                │                             │     required: ['y'],           │
│                                │                             │     properties: {              │
│                                │                             │       y: {                     │
│                                │                             │         type: 'number'         │
│                                │                             │       }                        │
│                                │                             │   }]                           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Composite([type T = {const T = {                    │
│   Type.Object({                │   x: number | string        │   type: 'object',              │
│     x: Type.Number()           │   y: number                 │   properties: {                │
│   }),}                           │     x: {                       │
│   Type.Object({                │                             │       anyOf: [                 │
│     x: Type.String()           │                             │         { type: 'number' },    │
│     y: Type.Number()           │                             │         { type: 'string' }     │
│   })                           │                             │       ]                        │
│ ])                             │                             │     },                         │
│                                │                             │     y: {                       │
│                                │                             │       type: 'number'           │
│                                │                             │     }                          │
│                                │                             │   },                           │
│                                │                             │   required: ['x', 'y']         │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Never()type T = neverconst T = {                    │
│                                │                             │   not: {}                      │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Not(            | type T = stringconst T = {|   Type.Union([                 │                             │   allOf: [{                    │
│     Type.Literal('x'),         │                             │     not: {                     │
│     Type.Literal('y'),         │                             │       anyOf: [                 │
│     Type.Literal('z')          │                             │         { const: 'x' },        │
│   ]),                          │                             │         { const: 'y' },        │
│   Type.String()                │                             │         { const: 'z' }         │
│ )                              │                             │       ]                        │
│                                │                             │     }                          │
│                                │                             │   }, {                         │
│                                │                             │     type: 'string'             │
│                                │                             │   }]                           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Extends(type T =const T = {                    │
│   Type.String(),string extends numberconst: false,                │
│   Type.Number(),true : false               │   type: 'boolean'              │
│   Type.Literal(true),          │                             │ }                              │
│   Type.Literal(false)          │                             │                                │
│ )                              │                             │                                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Extract(type T = Extract<const T = {                    │
│   Type.Union([string | number,          │   type: 'string'               │
│     Type.String(),string}                              │
│     Type.Number(),>                           │                                │
│   ]),                          │                             │                                │
│   Type.String()                │                             │                                │
│ )                              │                             │                                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Exclude(type T = Exclude<const T = {                    │
│   Type.Union([string | number,          │   type: 'number'               │
│     Type.String(),string}                              │
│     Type.Number(),>                           │                                │
│   ]),                          │                             │                                │
│   Type.String()                │                             │                                │
│ )                              │                             │                                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Record(type T = Record<const T = {                    │
│   Type.String(),string,                   │   type: 'object',              │
│   Type.Number()number,                   │   patternProperties: {         │
│ )>'^.*$': {                  │
│                                │                             │       type: 'number'           │
│                                │                             │     }                          │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Partial(type T = Partial<{const T = {                    │
│   Type.Object({                │   x: number,                │   type: 'object',              │
│     x: Type.Number(),          │   y: number                 │   properties: {                │
│     y: Type.Number()           | }>                          │     x: {                       │
│   })                           │                             │       type: 'number'           │
│ )                              │                             │     },                         │
│                                │                             │     y: {                       │
│                                │                             │       type: 'number'           │
│                                │                             │     }                          │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Required(type T = Required<{const T = {                    │
│   Type.Object({                │   x?: number,               │   type: 'object',              │
│     x: Type.Optional(          │   y?: number                │   required: ['x', 'y'],        │
│       Type.Number()            | }>                          │   properties: {                │
│     ),                         │                             │     x: {                       │
│     y: Type.Optional(          │                             │       type: 'number'           │
│       Type.Number()            │                             │     },                         │
│     )                          │                             │     y: {                       │
│   })                           │                             │       type: 'number'           │
│ )                              │                             │     }                          │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Pick(type T = Pick<{const T = {                    │
│   Type.Object({                │   x: number,                │   type: 'object',              │
│     x: Type.Number(),          │   y: number                 │   properties: {                │
│     y: Type.Number()           | }, 'x'>                     │     x: {                       │
│   }), ['x']                    │                             │       type: 'number'           │
│ )                              │                             │     }                          │
│                                │                             │   },                           │
│                                │                             │   required: ['x']              │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Omit(type T = Omit<{const T = {                    │
│   Type.Object({                │   x: number,                │   type: 'object',              │
│     x: Type.Number(),          │   y: number                 │   properties: {                │
│     y: Type.Number()           | }, 'x'>                     │     y: {                       │
│   }), ['x']                    │                             │       type: 'number'           │
│ )                              │                             │     }                          │
│                                │                             │   },                           │
│                                │                             │   required: ['y']              │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const A = Type.Object({type A = {const T = {                    │
│    x: Type.Number(),           │   x: number,                │   $ref: 'A'                    │
│    y: Type.Number()            │   y: number}                              │
│ }, { $id: 'T' })               | }                           │                                │
│                                │                             │                                │
│ const T = Type.Ref(A)type T = A                  │                                │
│                                │                             │                                │
│                                │                             │                                │
│                                │                             │                                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const A = Type.Object({type T = {const T = {                    │
│    x: Type.Number(),           │   x: number,                │   $id: 'T'                     │
│    y: Type.Number()            │   y: number                 │   type: 'object',              │
│ }, { $id: 'T' })               | }                           │   required: ['x', 'y'],        │
│                                │                             │   properties: {                │
│ const T = Type.Deref(          │                             │     x: { type: 'number' },     │
│   Type.Ref(A)                  │                             │     y: { type: 'number' },     │
│ )                              │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘

Extended Types

TypeBox provides several extended types that can be used to produce schematics for common JavaScript constructs. These types cannot be used with standard JSON schema validators; but are useful to help frame schematics for RPC interfaces that may receive JSON validated data. Extended types are prefixed with the [Extended] doc comment for convenience.

The following lists the supported types

┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
│ TypeBoxTypeScriptExtended Schema                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Constructor([type T = new (const T = {                    │
│   Type.String(),               │  arg0: string,              │   type: 'object',              │
│   Type.Number()                │  arg1: number               │   instanceOf: 'Constructor',   │
│ ], Type.Boolean())) => boolean                │   parameters: [{               │
│                                │                             │     type: 'string'             │
│                                │                             │   }, {                         │
│                                │                             │     type: 'number'             │
│                                │                             │   }],                          │
│                                │                             │   return: {                    │
│                                │                             │     type: 'boolean'            │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Function([type T = (const T = {|   Type.String(),               │  arg0: string,              │   type : 'object',             │
│   Type.Number()                │  arg1: number               │   instanceOf: 'Function',      │
│ ], Type.Boolean())) => boolean                │   parameters: [{               │
│                                │                             │     type: 'string'             │
│                                │                             │   }, {                         │
│                                │                             │     type: 'number'             │
│                                │                             │   }],                          │
│                                │                             │   return: {                    │
│                                │                             │     type: 'boolean'            │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Promise(type T = Promise<string>const T = {                    │
│   Type.String()                │                             │   type: 'object',              │
│ )                              │                             │   instanceOf: 'Promise',       │
│                                │                             │   item: {                      │
│                                │                             │     type: 'string'             │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Uint8Array()type T = Uint8Arrayconst T = {                    │
│                                │                             │   type: 'object',              │
│                                │                             │   instanceOf: 'Uint8Array'     │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Date()type T = Dateconst T = {                    │
│                                │                             │   type: 'object',              │
│                                │                             │   instanceOf: 'Date'           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Undefined()type T = undefinedconst T = {                    │
│                                │                             │   type: 'null',                │
│                                │                             │   typeOf: 'Undefined'          │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.RegEx(/foo/)type T = stringconst T = {                    │
│                                │                             │    type: 'string',             │
│                                │                             │    pattern: 'foo'              │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Symbol()type T = symbolconst T = {                    │
│                                │                             │   type: 'null',                │
│                                │                             │   typeOf: 'Symbol'             │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.BigInt()type T = bigint             │ const T = {                    │
│                                │                             │   type: 'null',                │
│                                │                             │   typeOf: 'BigInt'             │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Void()type T = voidconst T = {                    │
│                                │                             │   type: 'null'                 │
│                                │                             │   typeOf: 'Void'               │
│                                │                             │ }                              │
│                                │                             │                                │
└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘

Modifiers

TypeBox provides property modifier types that allow properties to be mapped with TypeScript readonly and optional. The following table shows the modifier types and how they map between TypeScript and JSON Schema.

┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
│ TypeBoxTypeScriptJSON Schema                    │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Object({type T = {const T = {                    │
│   name: Type.Optional(         │   name?: string             │   type: 'object',              │
│     Type.String()}                           │   properties: {                │
│   )                            │                             │     name: {                    │
│ })  	                         │                             │       type: 'string'           │
│                                │                             │     }                          │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Object({type T = {const T = {                    │
│   name: Type.Readonly(readonly name: string     │   type: 'object',              │
│     Type.String()}                           │   properties: {                │
│   )                            │                             │     name: {                    │
│ })  	                         │                             │       type: 'string'           │
│                                │                             │     }                          │
│                                │                             │   },                           │
│                                │                             │   required: ['name']           │
│                                │                             │ }                              │
│                                │                             │                                │
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
│ const T = Type.Object({type T = {const T = {                    │
│   name: Type.ReadonlyOptional(readonly name?: string    │   type: 'object',              │
│     Type.String()}                           │   properties: {                │
│   )                            │                             │     name: {                    │
│ })  	                         │                             │       type: 'string'           │
│                                │                             │     }                          │
│                                │                             │   }                            │
│                                │                             │ }                              │
│                                │                             │                                │
└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘

Options

You can pass JSON Schema compliant options on the last argument of any type. Option property hints are provided for convenience.

// String must be an email
const T = Type.String({                              // const T = { 
  format: 'email'                                    //   type: 'string',
})                                                   //   format: 'email' 
                                                     // }

// Mumber must be a multiple of 2
const T = Type.Number({                              // const T = { 
  multipleOf: 2                                      //  type: 'number', 
})                                                   //  multipleOf: 2 
                                                     // }

// Array must have at least 5 integer values
const T = Type.Array(Type.Integer(), {               // const T = { 
  minItems: 5                                        //   type: 'array',
})                                                   //   minItems: 5,        
                                                     //   items: { 
                                                     //     type: 'integer'
                                                     //   }
                                                     // }

Generic Types

Generic types can be created with generic functions. The following creates a generic Vector<T> type.

import { Type, Static, TSchema } from '@sinclair/typebox'

const Vector = <T extends TSchema>(t: T) => Type.Object({ x: t, y: t, z: t })

const NumberVector = Vector(Type.Number())           // const NumberVector = {
                                                     //   type: 'object',
                                                     //   required: ['x', 'y', 'z'],
                                                     //   properties: {
                                                     //     x: { type: 'number' },
                                                     //     y: { type: 'number' },
                                                     //     z: { type: 'number' }
                                                     //   }
                                                     // }

const BooleanVector = Vector(Type.Boolean())         // const BooleanVector = {
                                                     //   type: 'object',
                                                     //   required: ['x', 'y', 'z'],
                                                     //   properties: {
                                                     //     x: { type: 'boolean' },
                                                     //     y: { type: 'boolean' },
                                                     //     z: { type: 'boolean' }
                                                     //   }
                                                     // }

Reference Types

Reference types are supported with Type.Ref(...).

const T = Type.String({ $id: 'T' })                  // const T = {
                                                     //    $id: 'T',
                                                     //    type: 'string'
                                                     // }
                                             
const R = Type.Ref(T)                                // const R = {
                                                     //    $ref: 'T'
                                                     // }

Recursive Types

Recursive types are supported with Type.Recursive(...).

const Node = Type.Recursive(Node => Type.Object({    // const Node = {
  id: Type.String(),                                 //   $id: 'Node',
  nodes: Type.Array(Node)                            //   type: 'object',
}), { $id: 'Node' })                                 //   properties: {
                                                     //     id: {
                                                     //       type: 'string'
                                                     //     },
                                                     //     nodes: {
                                                     //       type: 'array',
                                                     //       items: {
                                                     //         $ref: 'Node'
                                                     //       }
                                                     //     }
                                                     //   },
                                                     //   required: [
                                                     //     'id',
                                                     //     'nodes'
                                                     //   ]
                                                     // }

type Node = Static<typeof Node>                      // type Node = {
                                                     //   id: string
                                                     //   nodes: Node[]
                                                     // }

function test(node: Node) {
  const id = node.nodes[0].nodes[0].id               // id is string
}

Conditional Types

Conditional types are supported with Extends, Exclude and Extract. These work the same as in TypeScript.

TypeScript

type T0 = string extends number ? true : false                                                 
//   ^ false
type T1 = Extract<string | number, number>                                                     
//   ^ number
type T2 = Exclude<string | number, number>                                                     
//   ^ string

TypeBox

const T0 = Type.Extends(Type.String(), Type.Number(), Type.Literal(true), Type.Literal(false)) 
//    ^ TLiteral<false>
const T1 = Type.Extract(Type.Union([Type.String(), Type.Number()]), Type.Number())             
//    ^ TNumber
const T2 = Type.Exclude(Type.Union([Type.String(), Type.Number()]), Type.Number())             
//    ^ TString<string>

Unsafe

Use Type.Unsafe(...) to create custom schemas with user defined inference rules.

const T = Type.Unsafe<string>({ type: 'number' })    // const T = {
                                                     //   type: 'number'
                                                     // }

type T = Static<typeof T>                            // type T = string

The Type.Unsafe(...) type allows for the expression of specific OpenAPI schema representations.

import { Type, Static, TSchema } from '@sinclair/typebox'

// Nullable<T>

function Nullable<T extends TSchema>(schema: T) {
  return Type.Unsafe<Static<T> | null>({ ...schema, nullable: true })
}

const T = Nullable(Type.String())                    // const T = {
                                                     //   type: 'string',
                                                     //   nullable: true
                                                     // }

type T = Static<typeof T>                            // type T = string | null

// StringEnum<string[]>

function StringEnum<T extends string[]>(values: [...T]) {
  return Type.Unsafe<T[number]>({ type: 'string', enum: values })
}

const T = StringEnum(['A', 'B', 'C'])                // const T = {
                                                     //   enum: ['A', 'B', 'C']
                                                     // }

type T = Static<typeof T>                            // type T = 'A' | 'B' | 'C'

Guards

TypeBox provides a TypeGuard module for reflection and type assertion.

import { Type, TypeGuard } from '@sinclair/typebox'

const T = Type.String()

if(TypeGuard.TString(T)) {
    
  // T is TString
}

Strict

TypeBox schemas contain the Kind and Modifier symbol properties. These properties are used for type composition and runtime type reflection. These properties are not strictly valid JSON schema; so in some cases it may be desirable to omit them. TypeBox provides a Type.Strict() function that will omit these properties if necessary.

const T = Type.Object({                              // const T = {
  name: Type.Optional(Type.String())                 //   [Kind]: 'Object',
})                                                   //   type: 'object',
                                                     //   properties: {
                                                     //     name: {
                                                     //       [Kind]: 'String',
                                                     //       type: 'string',
                                                     //       [Modifier]: 'Optional'
                                                     //     }
                                                     //   }
                                                     // }

const U = Type.Strict(T)                             // const U = {
                                                     //   type: 'object', 
                                                     //   properties: { 
                                                     //     name: { 
                                                     //       type: 'string' 
                                                     //     } 
                                                     //   } 
                                                     // }

Values

TypeBox provides an optional utility module that can be used to perform common operations on JavaScript values. This module includes functionality to create, check and cast values from types as well as check equality, clone, diff and patch JavaScript values. This module is provided via additional import.

import { Value } from '@sinclair/typebox/value'

Create

Use the Create function to create a value from a type. TypeBox will use default values if specified.

const T = Type.Object({ x: Type.Number(), y: Type.Number({ default: 42 }) })

const A = Value.Create(T)                            // const A = { x: 0, y: 42 }

Clone

Use the Clone function to deeply clone a value

const A = Value.Clone({ x: 1, y: 2, z: 3 })          // const A = { x: 1, y: 2, z: 3 }

Check

Use the Check function to type check a value

const T = Type.Object({ x: Type.Number() })

const R = Value.Check(T, { x: 1 })                   // const R = true

Convert

Use the Convert function to convert a value into its target type if a reasonable conversion is possible.

const T = Type.Object({ x: Type.Number(), y: Type.Number() })

const R1 = Value.Convert(T, { x: '3.14' })          // const R1 = { x: 3.14 }

const R2 = Value.Convert(T, { x: 'not a number' })  // const R2 = { x: 'not a number' }

Cast

Use the Cast function to cast a value into a type. The cast function will retain as much information as possible from the original value.

const T = Type.Object({ x: Type.Number(), y: Type.Number() }, { additionalProperties: false })

const X = Value.Cast(T, null)                        // const X = { x: 0, y: 0 }

const Y = Value.Cast(T, { x: 1 })                    // const Y = { x: 1, y: 0 }

const Z = Value.Cast(T, { x: 1, y: 2, z: 3 })        // const Z = { x: 1, y: 2 }

Equal

Use the Equal function to deeply check for value equality.

const R = Value.Equal(                               // const R = true
  { x: 1, y: 2, z: 3 },
  { x: 1, y: 2, z: 3 }
)

Hash

Use the Hash function to create a FNV1A-64 non cryptographic hash of a value.

const A = Value.Hash({ x: 1, y: 2, z: 3 })          // const A = 2910466848807138541n

const B = Value.Hash({ x: 1, y: 4, z: 3 })          // const B = 1418369778807423581n

Diff

Use the Diff function to produce a sequence of edits to transform one value into another.

const E = Value.Diff(                               // const E = [
  { x: 1, y: 2, z: 3 },                             //   { type: 'update', path: '/y', value: 4 },
  { y: 4, z: 5, w: 6 }                              //   { type: 'update', path: '/z', value: 5 },
)                                                   //   { type: 'insert', path: '/w', value: 6 },
                                                    //   { type: 'delete', path: '/x' }
                                                    // ]

Patch

Use the Patch function to apply edits

const A = { x: 1, y: 2 }

const B = { x: 3 }

const E = Value.Diff(A, B)                           // const E = [
                                                     //   { type: 'update', path: '/x', value: 3 },
                                                     //   { type: 'delete', path: '/y' }
                                                     // ]

const C = Value.Patch<typeof B>(A, E)                // const C = { x: 3 }

Errors

Use the Errors function enumerate validation errors.

const T = Type.Object({ x: Type.Number(), y: Type.Number() })

const R = [...Value.Errors(T, { x: '42' })]          // const R = [{
                                                     //   schema: { type: 'number' },
                                                     //   path: '/x',
                                                     //   value: '42',
                                                     //   message: 'Expected number'
                                                     // }, {
                                                     //   schema: { type: 'number' },
                                                     //   path: '/y',
                                                     //   value: undefined,
                                                     //   message: 'Expected number'
                                                     // }]

Pointer

Use ValuePointer to perform mutable updates on existing values using RFC6901 JSON Pointers.

import { ValuePointer } from '@sinclair/typebox/value'

const A = { x: 0, y: 0, z: 0 }

ValuePointer.Set(A, '/x', 1)                         // const A = { x: 1, y: 0, z: 0 }
ValuePointer.Set(A, '/y', 1)                         // const A = { x: 1, y: 1, z: 0 }
ValuePointer.Set(A, '/z', 1)                         // const A = { x: 1, y: 1, z: 1 }

TypeCheck

TypeBox types target JSON Schema draft 6 so are compatible with any validator that supports this specification. TypeBox also provides a built in type checking compiler designed specifically for high performance compilation and value assertion.

The following sections detail using Ajv and TypeBox's compiler infrastructure.

Ajv

The following shows the recommended setup for Ajv.

$ npm install ajv ajv-formats --save
import { Type }   from '@sinclair/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 C = ajv.compile(Type.Object({                
  x: Type.Number(),
  y: Type.Number(),
  z: Type.Number()
}))

const R = C({ x: 1, y: 2, z: 3 })                    // const R = true 

TypeCompiler

The TypeBox TypeCompiler is a high performance JIT compiler that transforms TypeBox types into optimized JavaScript validation routines. The compiler is tuned for fast compilation as well as fast value assertion. It is designed to serve as a validation backend that can be integrated into larger applications; but can also be used as a general purpose validator.

The TypeCompiler is provided as an optional import.

import { TypeCompiler } from '@sinclair/typebox/compiler'

Use the Compile(...) function to compile a type.

const C = TypeCompiler.Compile(Type.Object({         // const C: TypeCheck<TObject<{
  x: Type.Number(),                                  //     x: TNumber;
  y: Type.Number(),                                  //     y: TNumber;
  z: Type.Number()                                   //     z: TNumber;
}))                                                  // }>>

const R = C.Check({ x: 1, y: 2, z: 3 })              // const R = true

Use the Errors(...) function to produce diagnostic errors for a value. The Errors(...) function will return an iterator that if enumerated; will perform an exhaustive check across the entire value and yield any error found. For performance, this function should only be called after failed Check(...). Applications may also choose to yield only the first value to avoid exhaustive error generation.

const C = TypeCompiler.Compile(Type.Object({         // const C: TypeCheck<TObject<{
  x: Type.Number(),                                  //     x: TNumber;
  y: Type.Number(),                                  //     y: TNumber;
  z: Type.Number()                                   //     z: TNumber;
}))                                                  // }>>

const value = { }

const errors = [...C.Errors(value)]                  // const errors = [{
                                                     //   schema: { type: 'number' },
                                                     //   path: '/x',
                                                     //   value: undefined,
                                                     //   message: 'Expected number'
                                                     // }, {
                                                     //   schema: { type: 'number' },
                                                     //   path: '/y',
                                                     //   value: undefined,
                                                     //   message: 'Expected number'
                                                     // }, {
                                                     //   schema: { type: 'number' },
                                                     //   path: '/z',
                                                     //   value: undefined,
                                                     //   message: 'Expected number'
                                                     // }]

Compiled routines can be inspected with the .Code() function.

const C = TypeCompiler.Compile(Type.String())        // const C: TypeCheck<TString>

console.log(C.Code())                                // return function check(value) {
                                                     //   return (
                                                     //     (typeof value === 'string')
                                                     //   )
                                                     // }

TypeSystem

The TypeBox TypeSystem module provides functionality to define types above and beyond the Standard and Extended type sets as well as control various assertion polices. Configurations made to the TypeSystem module are observed by both TypeCompiler and Value modules.

The TypeSystem module is provided as an optional import.

import { TypeSystem } from '@sinclair/typebox/system'

Types

Use the Type(...) function to create a custom type. This function will return a type factory function that can be used to construct the type. The following creates a Point type.

type PointOptions = { }                              // The Type Options

type PointType = { x: number, y: number }            // The Static<T> Type

const Point = TypeSystem.Type<PointType, PointOptions>('Point', (options, value) => {
  return (
    typeof value === 'object' && value !== null &&
    typeof value.x === 'number' && 
    typeof value.y === 'number'
  )
})

const T = Point()

type T = Static<typeof T>                             // type T = { x: number, y: number }

const R = Value.Check(T, { x: 1, y: 2 })              // const R = true

Formats

Use the Format(...) function to create a custom string format. The following creates a custom string format that checks for lowercase strings.

TypeSystem.Format('lowercase', value => value === value.toLowerCase()) // format should be lowercase

const T = Type.String({ format: 'lowercase' })       

const A = Value.Check(T, 'action')                   // const A = true

const B = Value.Check(T, 'ACTION')                   // const B = false

Policies

TypeBox validates using JSON Schema assertion policies by default. It is possible to override these policies and have TypeBox assert using TypeScript policies. The following overrides are available.

// Allow arrays to validate as object types (default is false)
//
// const A: {} = [] - allowed in TS

TypeSystem.AllowArrayObjects = true                  

// Allow numeric values to be NaN or + or - Infinity (default is false)
//
// const A: number = NaN - allowed in TS

TypeSystem.AllowNaN = true                      

Benchmark

This project maintains a set of benchmarks that measure Ajv, Value and TypeCompiler compilation and validation performance. These benchmarks can be run locally by cloning this repository and running npm run benchmark. The results below show for Ajv version 8.11.2.

For additional comparative benchmarks, please refer to typescript-runtime-type-benchmarks.

Compile

This benchmark measures compilation performance for varying types. You can review this benchmark here.

┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┐
          (index)IterationsAjvTypeCompilerPerformance  │
├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┤
│ Literal_String1000'    252 ms''      8 ms''   31.50 x' │
│ Literal_Number1000'    198 ms''      5 ms''   39.60 x' │
│ Literal_Boolean1000'    183 ms''      6 ms''   30.50 x' │
│ Primitive_Number1000'    172 ms''     12 ms''   14.33 x' │
│ Primitive_String1000'    156 ms''     10 ms''   15.60 x' │
│ Primitive_Boolean1000'    137 ms''     10 ms''   13.70 x' │
│ Primitive_Null1000'    118 ms''      7 ms''   16.86 x' │
│ Primitive_RegEx1000'    235 ms''     11 ms''   21.36 x' │
│ Object_Unconstrained1000'   1183 ms''     39 ms''   30.33 x' │
│ Object_Constrained1000'   1164 ms''     35 ms''   33.26 x' │
│ Tuple_Primitive1000'    470 ms''     16 ms''   29.38 x' │
│ Tuple_Object1000'   1096 ms''     17 ms''   64.47 x' │
│ Composite_Intersect1000'    570 ms''     21 ms''   27.14 x' │
│ Composite_Union1000'    523 ms''     21 ms''   24.90 x' │
│ Math_Vector41000'    788 ms''     12 ms''   65.67 x' │
│ Math_Matrix41000'    389 ms''     12 ms''   32.42 x' │
│ Array_Primitive_Number1000'    291 ms''      6 ms''   48.50 x' │
│ Array_Primitive_String1000'    313 ms''      4 ms''   78.25 x' │
│ Array_Primitive_Boolean1000'    357 ms''      3 ms''  119.00 x' │
│ Array_Object_Unconstrained1000'   1551 ms''     19 ms''   81.63 x' │
│ Array_Object_Constrained1000'   1258 ms''     20 ms''   62.90 x' │
│ Array_Tuple_Primitive1000'    951 ms''     15 ms''   63.40 x' │
│ Array_Tuple_Object1000'   1157 ms''     14 ms''   82.64 x' │
│ Array_Composite_Intersect1000'    856 ms''     19 ms''   45.05 x' │
│ Array_Composite_Union1000'   1073 ms''     16 ms''   67.06 x' │
│ Array_Math_Vector41000'   1062 ms''     11 ms''   96.55 x' │
│ Array_Math_Matrix41000'    478 ms''      6 ms''   79.67 x' │
└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┘

Validate

This benchmark measures validation performance for varying types. You can review this benchmark here.

┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐
          (index)IterationsValueCheckAjvTypeCompilerPerformance  │
├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
│ Literal_String1000000'     24 ms''      6 ms''      5 ms''    1.20 x' │
│ Literal_Number1000000'     19 ms''     19 ms''     11 ms''    1.73 x' │
│ Literal_Boolean1000000'     19 ms''     18 ms''     10 ms''    1.80 x' │
│ Primitive_Number1000000'     25 ms''     17 ms''     11 ms''    1.55 x' │
│ Primitive_String1000000'     23 ms''     16 ms''     10 ms''    1.60 x' │
│ Primitive_Boolean1000000'     19 ms''     17 ms''     10 ms''    1.70 x' │
│ Primitive_Null1000000'     21 ms''     17 ms''     10 ms''    1.70 x' │
│ Primitive_RegEx1000000'    154 ms''     45 ms''     38 ms''    1.18 x' │
│ Object_Unconstrained1000000'    837 ms''     34 ms''     29 ms''    1.17 x' │
│ Object_Constrained1000000'   1045 ms''     52 ms''     45 ms''    1.16 x' │
│ Object_Recursive1000000'   4711 ms''    355 ms''    100 ms''    3.55 x' │
│ Tuple_Primitive1000000'    163 ms''     21 ms''     16 ms''    1.31 x' │
│ Tuple_Object1000000'    668 ms''     30 ms''     26 ms''    1.15 x' │
│ Composite_Intersect1000000'    682 ms''     28 ms''     21 ms''    1.33 x' │
│ Composite_Union1000000'    463 ms''     22 ms''     19 ms''    1.16 x' │
│ Math_Vector41000000'    255 ms''     22 ms''     13 ms''    1.69 x' │
│ Math_Matrix41000000'    988 ms''     38 ms''     29 ms''    1.31 x' │
│ Array_Primitive_Number1000000'    270 ms''     26 ms''     15 ms''    1.73 x' │
│ Array_Primitive_String1000000'    207 ms''     22 ms''     16 ms''    1.38 x' │
│ Array_Primitive_Boolean1000000'    137 ms''     21 ms''     19 ms''    1.11 x' │
│ Array_Object_Unconstrained1000000'   4698 ms''     68 ms''     61 ms''    1.11 x' │
│ Array_Object_Constrained1000000'   4863 ms''    139 ms''    117 ms''    1.19 x' │
│ Array_Object_Recursive1000000'  19170 ms''   1606 ms''    332 ms''    4.84 x' │
│ Array_Tuple_Primitive1000000'    724 ms''     38 ms''     31 ms''    1.23 x' │
│ Array_Tuple_Object1000000'   2843 ms''     71 ms''     63 ms''    1.13 x' │
│ Array_Composite_Intersect1000000'   2816 ms''     49 ms''     40 ms''    1.23 x' │
│ Array_Composite_Union1000000'   2021 ms''     69 ms''     39 ms''    1.77 x' │
│ Array_Math_Vector41000000'   1080 ms''     39 ms''     25 ms''    1.56 x' │
│ Array_Math_Matrix41000000'   4561 ms''    112 ms''     96 ms''    1.17 x' │
└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘

Compression

The following table lists esbuild compiled and minified sizes for each TypeBox module.

┌──────────────────────┬────────────┬────────────┬─────────────┐
       (index)CompiledMinifiedCompression │
├──────────────────────┼────────────┼────────────┼─────────────┤
│ typebox/compiler     │ '108.2 kb'' 48.5 kb''2.23 x'   │
│ typebox/errors       │ ' 92.9 kb'' 41.4 kb''2.24 x'   │
│ typebox/system       │ ' 59.7 kb'' 24.5 kb''2.43 x'   │
│ typebox/value        │ '153.3 kb'' 66.6 kb''2.30 x'   │
│ typebox              │ ' 58.7 kb'' 24.1 kb''2.43 x'   │
└──────────────────────┴────────────┴────────────┴─────────────┘

Contribute

TypeBox is open to community contribution. Please ensure you submit an open issue before submitting your pull request. The TypeBox project preferences open community discussion prior to accepting new features.