Gathering detailed insights and metrics for @sinclair/typebox
Gathering detailed insights and metrics for @sinclair/typebox
Gathering detailed insights and metrics for @sinclair/typebox
Gathering detailed insights and metrics for @sinclair/typebox
@coderspirit/nominal-typebox
Integration of @coderspirit/nominal with @sinclair/typebox
@sinclair/typebox-codegen
Code Generation Tools for TypeBox
@fastify/type-provider-typebox
A Type Provider for Typebox over Fastify
@n1k1t/typebox
Forked from @sinclair/typebox. JSONSchema Type Builder with Static Type Resolution for TypeScript
Json Schema Type Builder with Static Type Resolution for TypeScript
npm install @sinclair/typebox
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
5,090 Stars
557 Commits
162 Forks
16 Watching
9 Branches
45 Contributors
Updated on 28 Nov 2024
TypeScript (99.83%)
JavaScript (0.17%)
Cumulative downloads
Total Downloads
Last day
-10.4%
5,954,008
Compared to previous day
Last week
0.9%
34,643,919
Compared to previous week
Last month
8.5%
145,649,806
Compared to previous month
Last year
52.8%
1,524,983,833
Compared to previous year
No dependencies detected.
1$ npm install @sinclair/typebox --save
1import { Type, type Static } from '@sinclair/typebox' 2 3const T = Type.Object({ // const T = { 4 x: Type.Number(), // type: 'object', 5 y: Type.Number(), // required: ['x', 'y', 'z'], 6 z: Type.Number() // properties: { 7}) // x: { type: 'number' }, 8 // y: { type: 'number' }, 9 // z: { type: 'number' } 10 // } 11 // } 12 13type T = Static<typeof T> // type T = { 14 // x: number, 15 // y: number, 16 // z: number 17 // }
TypeBox is a runtime type builder 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 asserted 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
The following shows general usage.
1import { Type, type Static } from '@sinclair/typebox' 2 3//-------------------------------------------------------------------------------------------- 4// 5// Let's say you have the following type ... 6// 7//-------------------------------------------------------------------------------------------- 8 9type T = { 10 id: string, 11 name: string, 12 timestamp: number 13} 14 15//-------------------------------------------------------------------------------------------- 16// 17// ... you can express this type in the following way. 18// 19//-------------------------------------------------------------------------------------------- 20 21const T = Type.Object({ // const T = { 22 id: Type.String(), // type: 'object', 23 name: Type.String(), // properties: { 24 timestamp: Type.Integer() // id: { 25}) // type: 'string' 26 // }, 27 // name: { 28 // type: 'string' 29 // }, 30 // timestamp: { 31 // type: 'integer' 32 // } 33 // }, 34 // required: [ 35 // 'id', 36 // 'name', 37 // 'timestamp' 38 // ] 39 // } 40 41//-------------------------------------------------------------------------------------------- 42// 43// ... then infer back to the original static type this way. 44// 45//-------------------------------------------------------------------------------------------- 46 47type T = Static<typeof T> // type T = { 48 // id: string, 49 // name: string, 50 // timestamp: number 51 // } 52 53//-------------------------------------------------------------------------------------------- 54// 55// ... or use the type to parse JavaScript values. 56// 57//-------------------------------------------------------------------------------------------- 58 59import { Value } from '@sinclair/typebox/value' 60 61const R = Value.Parse(T, value) // const R: { 62 // id: string, 63 // name: string, 64 // timestamp: number 65 // }
TypeBox types are Json Schema fragments that compose into more complex types. Each fragment is structured such that any Json Schema compliant validator can runtime assert a value the same way TypeScript will statically assert a type. TypeBox offers a set of Json Types which are used to create Json Schema compliant schematics as well as a JavaScript type set used to create schematics for constructs native to JavaScript.
The following table lists the supported Json types. These types are fully compatible with the Json Schema Draft 7 specification.
1┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ 2│ TypeBox │ TypeScript │ Json Schema │ 3│ │ │ │ 4├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 5│ const T = Type.Any() │ type T = any │ const T = { } │ 6│ │ │ │ 7├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 8│ const T = Type.Unknown() │ type T = unknown │ const T = { } │ 9│ │ │ │ 10├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 11│ const T = Type.String() │ type T = string │ const T = { │ 12│ │ │ type: 'string' │ 13│ │ │ } │ 14│ │ │ │ 15├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 16│ const T = Type.Number() │ type T = number │ const T = { │ 17│ │ │ type: 'number' │ 18│ │ │ } │ 19│ │ │ │ 20├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 21│ const T = Type.Integer() │ type T = number │ const T = { │ 22│ │ │ type: 'integer' │ 23│ │ │ } │ 24│ │ │ │ 25├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 26│ const T = Type.Boolean() │ type T = boolean │ const T = { │ 27│ │ │ type: 'boolean' │ 28│ │ │ } │ 29│ │ │ │ 30├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 31│ const T = Type.Null() │ type T = null │ const T = { │ 32│ │ │ type: 'null' │ 33│ │ │ } │ 34│ │ │ │ 35├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 36│ const T = Type.Literal(42) │ type T = 42 │ const T = { │ 37│ │ │ const: 42, │ 38│ │ │ type: 'number' │ 39│ │ │ } │ 40│ │ │ │ 41├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 42│ const T = Type.Array( │ type T = number[] │ const T = { │ 43│ Type.Number() │ │ type: 'array', │ 44│ ) │ │ items: { │ 45│ │ │ type: 'number' │ 46│ │ │ } │ 47│ │ │ } │ 48│ │ │ │ 49├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 50│ const T = Type.Object({ │ type T = { │ const T = { │ 51│ x: Type.Number(), │ x: number, │ type: 'object', │ 52│ y: Type.Number() │ y: number │ required: ['x', 'y'], │ 53│ }) │ } │ properties: { │ 54│ │ │ x: { │ 55│ │ │ type: 'number' │ 56│ │ │ }, │ 57│ │ │ y: { │ 58│ │ │ type: 'number' │ 59│ │ │ } │ 60│ │ │ } │ 61│ │ │ } │ 62│ │ │ │ 63├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 64│ const T = Type.Tuple([ │ type T = [number, number] │ const T = { │ 65│ Type.Number(), │ │ type: 'array', │ 66│ Type.Number() │ │ items: [{ │ 67│ ]) │ │ type: 'number' │ 68│ │ │ }, { │ 69│ │ │ type: 'number' │ 70│ │ │ }], │ 71│ │ │ additionalItems: false, │ 72│ │ │ minItems: 2, │ 73│ │ │ maxItems: 2 │ 74│ │ │ } │ 75│ │ │ │ 76│ │ │ │ 77├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 78│ enum Foo { │ enum Foo { │ const T = { │ 79│ A, │ A, │ anyOf: [{ │ 80│ B │ B │ type: 'number', │ 81│ } │ } │ const: 0 │ 82│ │ │ }, { │ 83│ const T = Type.Enum(Foo) │ type T = Foo │ type: 'number', │ 84│ │ │ const: 1 │ 85│ │ │ }] │ 86│ │ │ } │ 87│ │ │ │ 88├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 89│ const T = Type.Const({ │ type T = { │ const T = { │ 90│ x: 1, │ readonly x: 1, │ type: 'object', │ 91│ y: 2, │ readonly y: 2 │ required: ['x', 'y'], │ 92│ } as const) │ } │ properties: { │ 93│ │ │ x: { │ 94│ │ │ type: 'number', │ 95│ │ │ const: 1 │ 96│ │ │ }, │ 97│ │ │ y: { │ 98│ │ │ type: 'number', │ 99│ │ │ const: 2 │ 100│ │ │ } │ 101│ │ │ } │ 102│ │ │ } │ 103│ │ │ │ 104├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 105│ const T = Type.KeyOf( │ type T = keyof { │ const T = { │ 106│ Type.Object({ │ x: number, │ anyOf: [{ │ 107│ x: Type.Number(), │ y: number │ type: 'string', │ 108│ y: Type.Number() │ } │ const: 'x' │ 109│ }) │ │ }, { │ 110│ ) │ │ type: 'string', │ 111│ │ │ const: 'y' │ 112│ │ │ }] │ 113│ │ │ } │ 114│ │ │ │ 115├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 116│ const T = Type.Union([ │ type T = string | number │ const T = { │ 117│ Type.String(), │ │ anyOf: [{ │ 118│ Type.Number() │ │ type: 'string' │ 119│ ]) │ │ }, { │ 120│ │ │ type: 'number' │ 121│ │ │ }] │ 122│ │ │ } │ 123│ │ │ │ 124├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 125│ const T = Type.Intersect([ │ type T = { │ const T = { │ 126│ Type.Object({ │ x: number │ allOf: [{ │ 127│ x: Type.Number() │ } & { │ type: 'object', │ 128│ }), │ y: number │ required: ['x'], │ 129│ Type.Object({ │ } │ properties: { │ 130│ y: Type.Number() │ │ x: { │ 131│ }) │ │ type: 'number' │ 132│ ]) │ │ } │ 133│ │ │ } │ 134│ │ │ }, { │ 135│ │ │ type: 'object', | 136│ │ │ required: ['y'], │ 137│ │ │ properties: { │ 138│ │ │ y: { │ 139│ │ │ type: 'number' │ 140│ │ │ } │ 141│ │ │ } │ 142│ │ │ }] │ 143│ │ │ } │ 144│ │ │ │ 145├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 146│ const T = Type.Composite([ │ type T = { │ const T = { │ 147│ Type.Object({ │ x: number, │ type: 'object', │ 148│ x: Type.Number() │ y: number │ required: ['x', 'y'], │ 149│ }), │ } │ properties: { │ 150│ Type.Object({ │ │ x: { │ 151│ y: Type.Number() │ │ type: 'number' │ 152│ }) │ │ }, │ 153│ ]) │ │ y: { │ 154│ │ │ type: 'number' │ 155│ │ │ } │ 156│ │ │ } │ 157│ │ │ } │ 158│ │ │ │ 159├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 160│ const T = Type.Never() │ type T = never │ const T = { │ 161│ │ │ not: {} │ 162│ │ │ } │ 163│ │ │ │ 164├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 165│ const T = Type.Not( | type T = unknown │ const T = { │ 166│ Type.String() │ │ not: { │ 167│ ) │ │ type: 'string' │ 168│ │ │ } │ 169│ │ │ } │ 170├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 171│ const T = Type.Extends( │ type T = │ const T = { │ 172│ Type.String(), │ string extends number │ const: false, │ 173│ Type.Number(), │ ? true │ type: 'boolean' │ 174│ Type.Literal(true), │ : false │ } │ 175│ Type.Literal(false) │ │ │ 176│ ) │ │ │ 177│ │ │ │ 178├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 179│ const T = Type.Extract( │ type T = Extract< │ const T = { │ 180│ Type.Union([ │ string | number, │ type: 'string' │ 181│ Type.String(), │ string │ } │ 182│ Type.Number(), │ > │ │ 183│ ]), │ │ │ 184│ Type.String() │ │ │ 185│ ) │ │ │ 186│ │ │ │ 187├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 188│ const T = Type.Exclude( │ type T = Exclude< │ const T = { │ 189│ Type.Union([ │ string | number, │ type: 'number' │ 190│ Type.String(), │ string │ } │ 191│ Type.Number(), │ > │ │ 192│ ]), │ │ │ 193│ Type.String() │ │ │ 194│ ) │ │ │ 195│ │ │ │ 196├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 197│ const T = Type.Mapped( │ type T = { │ const T = { │ 198│ Type.Union([ │ [_ in 'x' | 'y'] : number │ type: 'object', │ 199│ Type.Literal('x'), │ } │ required: ['x', 'y'], │ 200│ Type.Literal('y') │ │ properties: { │ 201│ ]), │ │ x: { │ 202│ () => Type.Number() │ │ type: 'number' │ 203│ ) │ │ }, │ 204│ │ │ y: { │ 205│ │ │ type: 'number' │ 206│ │ │ } │ 207│ │ │ } │ 208│ │ │ } │ 209│ │ │ │ 210├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 211│ const U = Type.Union([ │ type U = 'open' | 'close' │ const T = { │ 212│ Type.Literal('open'), │ │ type: 'string', │ 213│ Type.Literal('close') │ type T = `on${U}` │ pattern: '^on(open|close)$' │ 214│ ]) │ │ } │ 215│ │ │ │ 216│ const T = Type │ │ │ 217│ .TemplateLiteral([ │ │ │ 218│ Type.Literal('on'), │ │ │ 219│ U │ │ │ 220│ ]) │ │ │ 221│ │ │ │ 222├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 223│ const T = Type.Record( │ type T = Record< │ const T = { │ 224│ Type.String(), │ string, │ type: 'object', │ 225│ Type.Number() │ number │ patternProperties: { │ 226│ ) │ > │ '^.*$': { │ 227│ │ │ type: 'number' │ 228│ │ │ } │ 229│ │ │ } │ 230│ │ │ } │ 231│ │ │ │ 232├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 233│ const T = Type.Partial( │ type T = Partial<{ │ const T = { │ 234│ Type.Object({ │ x: number, │ type: 'object', │ 235│ x: Type.Number(), │ y: number │ properties: { │ 236│ y: Type.Number() | }> │ x: { │ 237│ }) │ │ type: 'number' │ 238│ ) │ │ }, │ 239│ │ │ y: { │ 240│ │ │ type: 'number' │ 241│ │ │ } │ 242│ │ │ } │ 243│ │ │ } │ 244│ │ │ │ 245├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 246│ const T = Type.Required( │ type T = Required<{ │ const T = { │ 247│ Type.Object({ │ x?: number, │ type: 'object', │ 248│ x: Type.Optional( │ y?: number │ required: ['x', 'y'], │ 249│ Type.Number() | }> │ properties: { │ 250│ ), │ │ x: { │ 251│ y: Type.Optional( │ │ type: 'number' │ 252│ Type.Number() │ │ }, │ 253│ ) │ │ y: { │ 254│ }) │ │ type: 'number' │ 255│ ) │ │ } │ 256│ │ │ } │ 257│ │ │ } │ 258│ │ │ │ 259├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 260│ const T = Type.Pick( │ type T = Pick<{ │ const T = { │ 261│ Type.Object({ │ x: number, │ type: 'object', │ 262│ x: Type.Number(), │ y: number │ required: ['x'], │ 263│ y: Type.Number() │ }, 'x'> │ properties: { │ 264│ }), ['x'] | │ x: { │ 265│ ) │ │ type: 'number' │ 266│ │ │ } │ 267│ │ │ } │ 268│ │ │ } │ 269│ │ │ │ 270├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 271│ const T = Type.Omit( │ type T = Omit<{ │ const T = { │ 272│ Type.Object({ │ x: number, │ type: 'object', │ 273│ x: Type.Number(), │ y: number │ required: ['y'], │ 274│ y: Type.Number() │ }, 'x'> │ properties: { │ 275│ }), ['x'] | │ y: { │ 276│ ) │ │ type: 'number' │ 277│ │ │ } │ 278│ │ │ } │ 279│ │ │ } │ 280│ │ │ │ 281├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 282│ const T = Type.Index( │ type T = { │ const T = { │ 283│ Type.Object({ │ x: number, │ type: 'number' │ 284│ x: Type.Number(), │ y: string │ } │ 285│ y: Type.String() │ }['x'] │ │ 286│ }), ['x'] │ │ │ 287│ ) │ │ │ 288│ │ │ │ 289├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 290│ const A = Type.Tuple([ │ type A = [0, 1] │ const T = { │ 291│ Type.Literal(0), │ type B = [2, 3] │ type: 'array', │ 292│ Type.Literal(1) │ type T = [ │ items: [ │ 293│ ]) │ ...A, │ { const: 0 }, │ 294│ const B = Type.Tuple([ │ ...B │ { const: 1 }, │ 295| Type.Literal(2), │ ] │ { const: 2 }, │ 296| Type.Literal(3) │ │ { const: 3 } │ 297│ ]) │ │ ], │ 298│ const T = Type.Tuple([ │ │ additionalItems: false, │ 299| ...Type.Rest(A), │ │ minItems: 4, │ 300| ...Type.Rest(B) │ │ maxItems: 4 │ 301│ ]) │ │ } │ 302│ │ │ │ 303├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 304│ const T = Type.Uncapitalize( │ type T = Uncapitalize< │ const T = { │ 305│ Type.Literal('Hello') │ 'Hello' │ type: 'string', │ 306│ ) │ > │ const: 'hello' │ 307│ │ │ } │ 308│ │ │ │ 309├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 310│ const T = Type.Capitalize( │ type T = Capitalize< │ const T = { │ 311│ Type.Literal('hello') │ 'hello' │ type: 'string', │ 312│ ) │ > │ const: 'Hello' │ 313│ │ │ } │ 314│ │ │ │ 315├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 316│ const T = Type.Uppercase( │ type T = Uppercase< │ const T = { │ 317│ Type.Literal('hello') │ 'hello' │ type: 'string', │ 318│ ) │ > │ const: 'HELLO' │ 319│ │ │ } │ 320│ │ │ │ 321├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 322│ const T = Type.Lowercase( │ type T = Lowercase< │ const T = { │ 323│ Type.Literal('HELLO') │ 'HELLO' │ type: 'string', │ 324│ ) │ > │ const: 'hello' │ 325│ │ │ } │ 326│ │ │ │ 327├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 328│ const R = Type.Ref('T') │ type R = unknown │ const R = { $ref: 'T' } │ 329│ │ │ │ 330└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
TypeBox provides an extended type set that can be used to create schematics for common JavaScript constructs. These types can not be used with any standard Json Schema validator; but can be used to frame schematics for interfaces that may receive Json validated data. JavaScript types are prefixed with the [JavaScript]
jsdoc comment for convenience. The following table lists the supported types.
1┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ 2│ TypeBox │ TypeScript │ Extended Schema │ 3│ │ │ │ 4├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 5│ const T = Type.Constructor([ │ type T = new ( │ const T = { │ 6│ Type.String(), │ arg0: string, │ type: 'Constructor', │ 7│ Type.Number() │ arg0: number │ parameters: [{ │ 8│ ], Type.Boolean()) │ ) => boolean │ type: 'string' │ 9│ │ │ }, { │ 10│ │ │ type: 'number' │ 11│ │ │ }], │ 12│ │ │ returns: { │ 13│ │ │ type: 'boolean' │ 14│ │ │ } │ 15│ │ │ } │ 16│ │ │ │ 17├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 18│ const T = Type.Function([ │ type T = ( │ const T = { │ 19| Type.String(), │ arg0: string, │ type: 'Function', │ 20│ Type.Number() │ arg1: number │ parameters: [{ │ 21│ ], Type.Boolean()) │ ) => boolean │ type: 'string' │ 22│ │ │ }, { │ 23│ │ │ type: 'number' │ 24│ │ │ }], │ 25│ │ │ returns: { │ 26│ │ │ type: 'boolean' │ 27│ │ │ } │ 28│ │ │ } │ 29│ │ │ │ 30├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 31│ const T = Type.Promise( │ type T = Promise<string> │ const T = { │ 32│ Type.String() │ │ type: 'Promise', │ 33│ ) │ │ item: { │ 34│ │ │ type: 'string' │ 35│ │ │ } │ 36│ │ │ } │ 37│ │ │ │ 38├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 39│ const T = │ type T = │ const T = { │ 40│ Type.AsyncIterator( │ AsyncIterableIterator< │ type: 'AsyncIterator', │ 41│ Type.String() │ string │ items: { │ 42│ ) │ > │ type: 'string' │ 43│ │ │ } │ 44│ │ │ } │ 45│ │ │ │ 46├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 47│ const T = Type.Iterator( │ type T = │ const T = { │ 48│ Type.String() │ IterableIterator<string> │ type: 'Iterator', │ 49│ ) │ │ items: { │ 50│ │ │ type: 'string' │ 51│ │ │ } │ 52│ │ │ } │ 53│ │ │ │ 54├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 55│ const T = Type.RegExp(/abc/i) │ type T = string │ const T = { │ 56│ │ │ type: 'RegExp' │ 57│ │ │ source: 'abc' │ 58│ │ │ flags: 'i' │ 59│ │ │ } │ 60│ │ │ │ 61├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 62│ const T = Type.Uint8Array() │ type T = Uint8Array │ const T = { │ 63│ │ │ type: 'Uint8Array' │ 64│ │ │ } │ 65│ │ │ │ 66├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 67│ const T = Type.Date() │ type T = Date │ const T = { │ 68│ │ │ type: 'Date' │ 69│ │ │ } │ 70│ │ │ │ 71├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 72│ const T = Type.Undefined() │ type T = undefined │ const T = { │ 73│ │ │ type: 'undefined' │ 74│ │ │ } │ 75│ │ │ │ 76├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 77│ const T = Type.Symbol() │ type T = symbol │ const T = { │ 78│ │ │ type: 'symbol' │ 79│ │ │ } │ 80│ │ │ │ 81├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 82│ const T = Type.BigInt() │ type T = bigint │ const T = { │ 83│ │ │ type: 'bigint' │ 84│ │ │ } │ 85│ │ │ │ 86├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 87│ const T = Type.Void() │ type T = void │ const T = { │ 88│ │ │ type: 'void' │ 89│ │ │ } │ 90│ │ │ │ 91└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
Import the Type namespace to bring in the full TypeBox type system. This is recommended for most users.
1import { Type, type Static } from '@sinclair/typebox'
You can also selectively import types. This enables modern bundlers to tree shake for unused types.
1import { Object, Number, String, Boolean, type Static } from '@sinclair/typebox'
You can pass Json Schema options on the last argument of any given type. Option hints specific to each type are provided for convenience.
1// String must be an email 2const T = Type.String({ // const T = { 3 format: 'email' // type: 'string', 4}) // format: 'email' 5 // } 6 7// Number must be a multiple of 2 8const T = Type.Number({ // const T = { 9 multipleOf: 2 // type: 'number', 10}) // multipleOf: 2 11 // } 12 13// Array must have at least 5 integer values 14const T = Type.Array(Type.Integer(), { // const T = { 15 minItems: 5 // type: 'array', 16}) // minItems: 5, 17 // items: { 18 // type: 'integer' 19 // } 20 // }
Object properties can be modified with Readonly and Optional. The following table shows how these modifiers map between TypeScript and Json Schema.
1┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ 2│ TypeBox │ TypeScript │ Json Schema │ 3│ │ │ │ 4├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 5│ const T = Type.Object({ │ type T = { │ const T = { │ 6│ name: Type.ReadonlyOptional( │ readonly name?: string │ type: 'object', │ 7│ Type.String() │ } │ properties: { │ 8│ ) │ │ name: { │ 9│ }) │ │ type: 'string' │ 10│ │ │ } │ 11│ │ │ } │ 12│ │ │ } │ 13│ │ │ │ 14├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 15│ const T = Type.Object({ │ type T = { │ const T = { │ 16│ name: Type.Readonly( │ readonly name: string │ type: 'object', │ 17│ Type.String() │ } │ properties: { │ 18│ ) │ │ name: { │ 19│ }) │ │ type: 'string' │ 20│ │ │ } │ 21│ │ │ }, │ 22│ │ │ required: ['name'] │ 23│ │ │ } │ 24│ │ │ │ 25├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ 26│ const T = Type.Object({ │ type T = { │ const T = { │ 27│ name: Type.Optional( │ name?: string │ type: 'object', │ 28│ Type.String() │ } │ properties: { │ 29│ ) │ │ name: { │ 30│ }) │ │ type: 'string' │ 31│ │ │ } │ 32│ │ │ } │ 33│ │ │ } │ 34│ │ │ │ 35└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
Generic types can be created with functions. TypeBox types extend the TSchema interface so you should constrain parameters to this type. The following creates a generic Vector type.
1import { Type, type Static, type TSchema } from '@sinclair/typebox' 2 3const Vector = <T extends TSchema>(T: T) => 4 Type.Object({ // type Vector<T> = { 5 x: T, // x: T, 6 y: T, // y: T, 7 z: T // z: T 8 }) // } 9 10const NumberVector = Vector(Type.Number()) // type NumberVector = Vector<number>
Generic types are often used to create aliases for complex types. The following creates a Nullable generic type.
1const Nullable = <T extends TSchema>(schema: T) => Type.Union([schema, Type.Null()]) 2 3const T = Nullable(Type.String()) // const T = { 4 // anyOf: [ 5 // { type: 'string' }, 6 // { type: 'null' } 7 // ] 8 // } 9 10type T = Static<typeof T> // type T = string | null
TypeBox Modules are containers for related types. They provide a referential namespace, enabling types to reference one another via string identifiers. Modules support both singular and mutually recursive referencing within the context of a module, as well as referential computed types (such as Partial + Ref). All Module types must be imported before use. TypeBox represents an imported type with the $defs
Json Schema keyword.
The following creates a Module with User and PartialUser types. Note that the PartialUser type is specified as a Partial + Ref to the User type. It is not possible to perform a Partial operation directly on a reference, so TypeBox will return a TComputed type that defers the Partial operation until all types are resolved. The TComputed type is evaluated when calling Import on the Module.
1// Module with PartialUser and User types 2 3const Module = Type.Module({ 4 5 PartialUser: Type.Partial(Type.Ref('User')), // TComputed<'Partial', [TRef<'User'>]> 6 7 User: Type.Object({ // TObject<{ 8 id: Type.String(), // user: TString, 9 name: Type.String(), // name: TString, 10 email: Type.String() // email: TString 11 }), // }> 12 13}) 14 15// Types must be imported before use. 16 17const User = Module.Import('User') // const User: TImport<{...}, 'User'> 18 19type User = Static<typeof User> // type User = { 20 // id: string, 21 // name: string, 22 // email: string 23 // } 24 25const PartialUser = Module.Import('PartialUser') // const PartialUser: TImport<{...}, 'PartialUser'> 26 27type PartialUser = Static<typeof PartialUser> // type PartialUser = { 28 // id?: string, 29 // name?: string, 30 // email?: string 31 // }
TypeBox supports template literal types with the TemplateLiteral function. This type can be created using a syntax similar to the TypeScript template literal syntax or composed from exterior types. TypeBox encodes template literals as regular expressions which enables the template to be checked by Json Schema validators. This type also supports regular expression parsing that enables template patterns to be used for generative types. The following shows both TypeScript and TypeBox usage.
1// TypeScript 2 3type K = `prop${'A'|'B'|'C'}` // type T = 'propA' | 'propB' | 'propC' 4 5type R = Record<K, string> // type R = { 6 // propA: string 7 // propB: string 8 // propC: string 9 // } 10 11// TypeBox 12 13const K = Type.TemplateLiteral('prop${A|B|C}') // const K: TTemplateLiteral<[ 14 // TLiteral<'prop'>, 15 // TUnion<[ 16 // TLiteral<'A'>, 17 // TLiteral<'B'>, 18 // TLiteral<'C'>, 19 // ]> 20 // ]> 21 22const R = Type.Record(K, Type.String()) // const R: TObject<{ 23 // propA: TString, 24 // propB: TString, 25 // propC: TString, 26 // }>
TypeBox supports indexed access types with the Index function. This function enables uniform access to interior property and element types without having to extract them from the underlying schema representation. Index types are supported for Object, Array, Tuple, Union and Intersect types.
1const T = Type.Object({ // type T = { 2 x: Type.Number(), // x: number, 3 y: Type.String(), // y: string, 4 z: Type.Boolean() // z: boolean 5}) // } 6 7const A = Type.Index(T, ['x']) // type A = T['x'] 8 // 9 // ... evaluated as 10 // 11 // const A: TNumber 12 13const B = Type.Index(T, ['x', 'y']) // type B = T['x' | 'y'] 14 // 15 // ... evaluated as 16 // 17 // const B: TUnion<[ 18 // TNumber, 19 // TString, 20 // ]> 21 22const C = Type.Index(T, Type.KeyOf(T)) // type C = T[keyof T] 23 // 24 // ... evaluated as 25 // 26 // const C: TUnion<[ 27 // TNumber, 28 // TString, 29 // TBoolean 30 // ]>
TypeBox supports mapped types with the Mapped function. This function accepts two arguments, the first is a union type typically derived from KeyOf, the second is a mapping function that receives a mapping key K
that can be used to index properties of a type. The following implements a mapped type that remaps each property to be T | null
1const T = Type.Object({ // type T = { 2 x: Type.Number(), // x: number, 3 y: Type.String(), // y: string, 4 z: Type.Boolean() // z: boolean 5}) // } 6 7const M = Type.Mapped(Type.KeyOf(T), K => { // type M = { [K in keyof T]: T[K] | null } 8 return Type.Union([Type.Index(T, K), Type.Null()]) // 9}) // ... evaluated as 10 // 11 // const M: TObject<{ 12 // x: TUnion<[TNumber, TNull]>, 13 // y: TUnion<[TString, TNull]>, 14 // z: TUnion<[TBoolean, TNull]> 15 // }>
TypeBox supports runtime conditional types with the Extends function. This function performs a structural assignability check against the first (left
) and second (right
) arguments and will return either the third (true
) or fourth (false
) argument based on the result. The conditional types Exclude and Extract are also supported. The following shows both TypeScript and TypeBox examples of conditional types.
1// Extends 2const A = Type.Extends( // type A = string extends number ? 1 : 2 3 Type.String(), // 4 Type.Number(), // ... evaluated as 5 Type.Literal(1), // 6 Type.Literal(2) // const A: TLiteral<2> 7) 8 9// Extract 10const B = Type.Extract( // type B = Extract<1 | 2 | 3, 1> 11 Type.Union([ // 12 Type.Literal(1), // ... evaluated as 13 Type.Literal(2), // 14 Type.Literal(3) // const B: TLiteral<1> 15 ]), 16 Type.Literal(1) 17) 18 19// Exclude 20const C = Type.Exclude( // type C = Exclude<1 | 2 | 3, 1> 21 Type.Union([ // 22 Type.Literal(1), // ... evaluated as 23 Type.Literal(2), // 24 Type.Literal(3) // const C: TUnion<[ 25 ]), // TLiteral<2>, 26 Type.Literal(1) // TLiteral<3>, 27) // ]>
TypeBox supports value decoding and encoding with Transform types. These types work in tandem with the Encode and Decode functions available on the Value and TypeCompiler submodules. Transform types can be used to convert Json encoded values into constructs more natural to JavaScript. The following creates a Transform type to decode numbers into Dates using the Value submodule.
1import { Value } from '@sinclair/typebox/value' 2 3const T = Type.Transform(Type.Number()) 4 .Decode(value => new Date(value)) // decode: number to Date 5 .Encode(value => value.getTime()) // encode: Date to number 6 7const D = Value.Decode(T, 0) // const D = Date(1970-01-01T00:00:00.000Z) 8const E = Value.Encode(T, D) // const E = 0
Use the StaticEncode or StaticDecode types to infer a Transform type.
1import { Static, StaticDecode, StaticEncode } from '@sinclair/typebox' 2 3const T = Type.Transform(Type.Array(Type.Number(), { uniqueItems: true })) 4 .Decode(value => new Set(value)) 5 .Encode(value => [...value]) 6 7type D = StaticDecode<typeof T> // type D = Set<number> 8type E = StaticEncode<typeof T> // type E = Array<number> 9type T = Static<typeof T> // type T = Array<number>
TypeBox supports user defined types with Unsafe. This type allows you to specify both schema representation and inference type. The following creates an Unsafe type with a number schema that infers as string.
1const T = Type.Unsafe<string>({ type: 'number' }) // const T = { type: 'number' } 2 3type T = Static<typeof T> // type T = string - ?
The Unsafe type is often used to create schematics for extended specifications like OpenAPI.
1 2const Nullable = <T extends TSchema>(schema: T) => Type.Unsafe<Static<T> | null>({ 3 ...schema, nullable: true 4}) 5 6const T = Nullable(Type.String()) // const T = { 7 // type: 'string', 8 // nullable: true 9 // } 10 11type T = Static<typeof T> // type T = string | null 12 13const StringEnum = <T extends string[]>(values: [...T]) => Type.Unsafe<T[number]>({ 14 type: 'string', enum: values 15}) 16const S = StringEnum(['A', 'B', 'C']) // const S = { 17 // enum: ['A', 'B', 'C'] 18 // } 19 20type S = Static<typeof T> // type S = 'A' | 'B' | 'C'
TypeBox can check its own types with the TypeGuard module. This module is written for type introspection and provides structural tests for every built-in TypeBox type. Functions of this module return is
guards which can be used with control flow assertions to obtain schema inference for unknown values. The following guards that the value T
is TString.
1import { TypeGuard, Kind } from '@sinclair/typebox' 2 3const T = { [Kind]: 'String', type: 'string' } 4 5if(TypeGuard.IsString(T)) { 6 7 // T is TString 8}
TypeBox has support for parsing TypeScript type annotations directly into TypeBox types. This feature supports both runtime and static parsing, with TypeBox implementing TypeScript parsers within the TypeScript type system itself. Syntax Types use the TypeBox Json Schema representations as an AST target for TypeScript types, providing a direct mapping between TypeScript syntax and Json Schema. Syntax Types are offered as a syntactical frontend to the Standard Type Builder API.
This feature is available via optional import.
1import { Parse } from '@sinclair/typebox/syntax'
Use the Parse function to transform a TypeScript type annotation into a TypeBox type. This function will return the parsed TypeBox type or undefined on error.
1const A = Parse('string') // const A: TString 2 3const B = Parse('[1, 2, 3]') // const B: TTuple<[ 4 // TLiteral<1>, 5 // TLiteral<2>, 6 // TLiteral<3> 7 // ]> 8 9const C = Parse(`{ x: number, y: number }`) // const C: TObject<{ 10 // x: TNumber 11 // y: TNumber 12 // }>
Syntax Types can compose with Standard Types created via the Type Builder API
1const T = Type.Object({ // const T: TObject<{ 2 x: Parse('number'), // x: TNumber, 3 y: Parse('string'), // y: TString, 4 z: Parse('boolean') // z: TBoolean 5}) // }>
Standard Types can also be passed to and referenced within Syntax Types.
1const X = Type.Number() 2const Y = Type.String() 3const Z = Type.Boolean() 4 5const T = Parse({ X, Y, Z }, `{ 6 x: X, 7 y: Y, 8 z: Z 9}`)
Syntax Types also support Module parsing.
1const Foo = Parse(`module Foo { 2 3 export type PartialUser = Pick<User, 'id'> & Partial<Omit<User, 'id'>> 4 5 export interface User { 6 id: string 7 name: string 8 email: string 9 } 10 11}`) 12 13const PartialUser = Foo.Import('PartialUser') // TImport<{...}, 'PartialUser'> 14 15type PartialUser = Static<typeof PartialUser> // type PartialUser = { 16 // id: string, 17 // } & { 18 // name?: string, 19 // email?: string, 20 // }
Syntax Types provide two Static types specific to inferring TypeBox and TypeScript types from strings.
1import { StaticParseAsSchema, StaticParseAsType } from '@sinclair/typebox/syntax' 2 3// Will infer as a TSchema 4 5type S = StaticParseAsSchema<{}, '{ x: number }'> // type S: TObject<{ 6 // x: TNumber 7 // }> 8 9// Will infer as a type 10 11type T = StaticParseAsType<{}, '{ x: number }'> // type T = { 12 // x: number 13 // }
TypeBox parses TypeScript types directly within the TypeScript type system. This process does come with an inference cost, which scales with the size and complexity of the types being parsed. Although TypeBox strives to optimize Syntax Types, users should be aware of the following structures:
1// Excessively wide structures will result in instantiation limits exceeding 2const A = Parse(`[ 3 0, 1, 2, 3, 4, 5, 6, 7, 4 0, 1, 2, 3, 4, 5, 6, 7, 5 0, 1, 2, 3, 4, 5, 6, 7, 6 0, 1, 2, 3, 4, 5, 6, 7, 7 0, 1, 2, 3, 4, 5, 6, 7, 8 0, 1, 2, 3, 4, 5, 6, 7, 9 0, 1, 2, 3, 4, 5, 6, 7, 10 0, 1, 2, 3, 4, 5, 6, 7, 11]`) 12 13// Excessively nested structures will result in instantiation limits exceeding 14const B = Parse(`{ 15 x: { 16 y: { 17 z: { 18 w: 1 <-- Type instantiation is excessively deep and possibly infinite. 19 } 20 } 21 } 22}`)
If Syntax Types exceed TypeScript's instantiation limits, users are advised to fall back to the Standard Type Builder API. Alternatively, TypeBox offers a ParseOnly
function that parses the TypeScript syntax at runtime without statically inferring the schema.
1import { ParseOnly } from '@sinclair/typebox/syntax' 2 3// const A: TSchema | undefined 4 5const A = ParseOnly(`{ 6 x: { 7 y: { 8 z: { 9 w: 1 10 } 11 } 12 } 13}`)
For more information on static parsing, refer to the ParseBox project.
TypeBox provides an optional Value submodule that can be used to perform structural operations on JavaScript values. This submodule includes functionality to create, check and cast values from types as well as check equality, clone, diff and patch JavaScript values. This submodule is provided via optional import.
1import { Value } from '@sinclair/typebox/value'
Use the Assert function to assert a value is valid.
1let value: unknown = 1 2 3Value.Assert(Type.Number(), value) // throws AssertError if invalid
Use the Create function to create a value from a type. TypeBox will use default values if specified.
1const T = Type.Object({ x: Type.Number(), y: Type.Number({ default: 42 }) }) 2 3const A = Value.Create(T) // const A = { x: 0, y: 42 }
Use the Clone function to deeply clone a value.
1const A = Value.Clone({ x: 1, y: 2, z: 3 }) // const A = { x: 1, y: 2, z: 3 }
Use the Check function to type check a value.
1const T = Type.Object({ x: Type.Number() }) 2 3const R = Value.Check(T, { x: 1 }) // const R = true
Use the Convert function to convert a value into its target type if a reasonable conversion is possible. This function may return an invalid value and should be checked before use. Its return type is unknown
.
1const T = Type.Object({ x: Type.Number() }) 2 3const R1 = Value.Convert(T, { x: '3.14' }) // const R1 = { x: 3.14 } 4 5const R2 = Value.Convert(T, { x: 'not a number' }) // const R2 = { x: 'not a number' }
Use Clean to remove excess properties from a value. This function does not check the value and returns an unknown type. You should Check the result before use. Clean is a mutable operation. To avoid mutation, Clone the value first.
1const T = Type.Object({ 2 x: Type.Number(), 3 y: Type.Number() 4}) 5 6const X = Value.Clean(T, null) // const 'X = null 7 8const Y = Value.Clean(T, { x: 1 }) // const 'Y = { x: 1 } 9 10const Z = Value.Clean(T, { x: 1, y: 2, z: 3 }) // const 'Z = { x: 1, y: 2 }
Use Default to generate missing properties on a value using default schema annotations if available. This function does not check the value and returns an unknown type. You should Check the result before use. Default is a mutable operation. To avoid mutation, Clone the value first.
1const T = Type.Object({ 2 x: Type.Number({ default: 0 }), 3 y: Type.Number({ default: 0 }) 4}) 5 6const X = Value.Default(T, null) // const 'X = null - non-enumerable 7 8const Y = Value.Default(T, { }) // const 'Y = { x: 0, y: 0 } 9 10const Z = Value.Default(T, { x: 1 }) // const 'Z = { x: 1, y: 0 }
Use the Cast function to upcast a value into a target type. This function will retain as much infomation as possible from the original value. The Cast function is intended to be used in data migration scenarios where existing values need to be upgraded to match a modified type.
1const T = Type.Object({ x: Type.Number(), y: Type.Number() }, { additionalProperties: false }) 2 3const X = Value.Cast(T, null) // const X = { x: 0, y: 0 } 4 5const Y = Value.Cast(T, { x: 1 }) // const Y = { x: 1, y: 0 } 6 7const Z = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const Z = { x: 1, y: 2 }
Use the Decode function to decode a value from a type or throw if the value is invalid. The return value will infer as the decoded type. This function will run Transform codecs if available.
1const A = Value.Decode(Type.String(), 'hello') // const A = 'hello' 2 3const B = Value.Decode(Type.String(), 42) // throw
Use the Encode function to encode a value to a type or throw if the value is invalid. The return value will infer as the encoded type. This function will run Transform codecs if available.
1const A = Value.Encode(Type.String(), 'hello') // const A = 'hello' 2 3const B = Value.Encode(Type.String(), 42) // throw
Use the Parse function to parse a value. This function calls the Clone
Clean
, Default
, Convert
, Assert
and Decode
Value functions in this exact order to process a value.
1const R = Value.Parse(Type.String(), 'hello') // const R: string = "hello" 2 3const E = Value.Parse(Type.String(), undefined) // throws AssertError
You can override the order in which functions are run, or omit functions entirely using the following.
1// Runs no functions. 2 3const R = Value.Parse([], Type.String(), 12345) 4 5// Runs the Assert() function. 6 7const E = Value.Parse(['Assert'], Type.String(), 12345) 8 9// Runs the Convert() function followed by the Assert() function. 10 11const S = Value.Parse(['Convert', 'Assert'], Type.String(), 12345)
Use the Equal function to deeply check for value equality.
1const R = Value.Equal( // const R = true 2 { x: 1, y: 2, z: 3 }, 3 { x: 1, y: 2, z: 3 } 4)
Use the Hash function to create a FNV1A-64 non cryptographic hash of a value.
1const A = Value.Hash({ x: 1, y: 2, z: 3 }) // const A = 2910466848807138541n 2 3const B = Value.Hash({ x: 1, y: 4, z: 3 }) // const B = 1418369778807423581n
Use the Diff function to generate a sequence of edits that will transform one value into another.
1const E = Value.Diff( // const E = [ 2 { x: 1, y: 2, z: 3 }, // { type: 'update', path: '/y', value: 4 }, 3 { y: 4, z: 5, w: 6 } // { type: 'update', path: '/z', value: 5 }, 4) // { type: 'insert', path: '/w', value: 6 }, 5 // { type: 'delete', path: '/x' } 6 // ]
Use the Patch function to apply a sequence of edits.
1const A = { x: 1, y: 2 } 2 3const B = { x: 3 } 4 5const E = Value.Diff(A, B) // const E = [ 6 // { type: 'update', path: '/x', value: 3 }, 7 // { type: 'delete', path: '/y' } 8 // ] 9 10const C = Value.Patch<typeof B>(A, E) // const C = { x: 3 }
Use the Errors function to enumerate validation errors.
1const T = Type.Object({ x: Type.Number(), y: Type.Number() }) 2 3const R = [...Value.Errors(T, { x: '42' })] // const R = [{ 4 // schema: { type: 'number' }, 5 // path: '/x', 6 // value: '42', 7 // message: 'Expected number' 8 // }, { 9 // schema: { type: 'number' }, 10 // path: '/y', 11 // value: undefined, 12 // message: 'Expected number' 13 // }]
Use the Mutate function to perform a deep mutable value assignment while retaining internal references.
1const Y = { z: 1 } // const Y = { z: 1 } 2const X = { y: Y } // const X = { y: { z: 1 } } 3const A = { x: X } // const A = { x: { y: { z: 1 } } } 4 5Value.Mutate(A, { x: { y: { z: 2 } } }) // A' = { x: { y: { z: 2 } } } 6 7const R0 = A.x.y.z === 2 // const R0 = true 8const R1 = A.x.y === Y // const R1 = true 9const R2 = A.x === X // const R2 = true
Use ValuePointer to perform mutable updates on existing values using RFC6901 Json Pointers.
1import { ValuePointer } from '@sinclair/typebox/value' 2 3const A = { x: 0, y: 0, z: 0 } 4 5ValuePointer.Set(A, '/x', 1) // A' = { x: 1, y: 0, z: 0 } 6ValuePointer.Set(A, '/y', 1) // A' = { x: 1, y: 1, z: 0 } 7ValuePointer.Set(A, '/z', 1) // A' = { x: 1, y: 1, z: 1 }
The TypeBox type system can be extended with additional types and formats using the TypeRegistry and FormatRegistry modules. These modules integrate deeply with TypeBox's internal type checking infrastructure and can be used to create application specific types, or register schematics for alternative specifications.
Use the TypeRegistry to register a type. The Kind must match the registered type name.
1import { TSchema, Kind, TypeRegistry } from '@sinclair/typebox' 2 3TypeRegistry.Set('Foo', (schema, value) => value === 'foo') 4 5const Foo = { [Kind]: 'Foo' } as TSchema 6 7const A = Value.Check(Foo, 'foo') // const A = true 8 9const B = Value.Check(Foo, 'bar') // const B = false
Use the FormatRegistry to register a string format.
1import { FormatRegistry } from '@sinclair/typebox' 2 3FormatRegistry.Set('foo', (value) => value === 'foo') 4 5const T = Type.String({ format: 'foo' }) 6 7const A = Value.Check(T, 'foo') // const A = true 8 9const B = Value.Check(T, 'bar') // const B = false
TypeBox types target Json Schema Draft 7 and are compatible with any validator that supports this specification. TypeBox also provides a built in type checking compiler designed specifically for TypeBox types that offers high performance compilation and value checking.
The following sections detail using Ajv and the TypeBox compiler infrastructure.
The following shows the recommended setup for Ajv.
1$ npm install ajv ajv-formats --save
1import { Type } from '@sinclair/typebox' 2import addFormats from 'ajv-formats' 3import Ajv from 'ajv' 4 5const ajv = addFormats(new Ajv({}), [ 6 'date-time', 7 'time', 8 'date', 9 'email', 10 'hostname', 11 'ipv4', 12 'ipv6', 13 'uri', 14 'uri-reference', 15 'uuid', 16 'uri-template', 17 'json-pointer', 18 'relative-json-pointer', 19 'regex' 20]) 21 22const validate = ajv.compile(Type.Object({ 23 x: Type.Number(), 24 y: Type.Number(), 25 z: Type.Number() 26})) 27 28const R = validate({ x: 1, y: 2, z: 3 }) // const R = true
The TypeBox TypeCompiler is a high performance JIT validation 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 built to serve as a validation backend that can be integrated into larger applications. It can also be used for code generation.
The TypeCompiler is provided as an optional import.
1import { TypeCompiler } from '@sinclair/typebox/compiler'
Use the Compile function to JIT compile a type. Note that compilation is generally an expensive operation and should only be performed once per type during application start up. TypeBox does not cache previously compiled types, and applications are expected to hold references to each compiled type for the lifetime of the application.
1const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{ 2 x: Type.Number(), // x: TNumber; 3 y: Type.Number(), // y: TNumber; 4 z: Type.Number() // z: TNumber; 5})) // }>> 6 7const R = C.Check({ x: 1, y: 2, z: 3 }) // const R = true
Use the Errors function to generate diagnostic errors for a value. The Errors function will return an iterator that when enumerated; will perform an exhaustive check across the entire value yielding any error found. For performance, this function should only be called after a failed Check. Applications may also choose to yield only the first value to avoid exhaustive error generation.
1const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{ 2 x: Type.Number(), // x: TNumber; 3 y: Type.Number(), // y: TNumber; 4 z: Type.Number() // z: TNumber; 5})) // }>> 6 7const value = { } 8 9const first = C.Errors(value).First() // const first = { 10 // schema: { type: 'number' }, 11 // path: '/x', 12 // value: undefined, 13 // message: 'Expected number' 14 // } 15 16const all = [...C.Errors(value)] // const all = [{ 17 // schema: { type: 'number' }, 18 // path: '/x', 19 // value: undefined, 20 // message: 'Expected number' 21 // }, { 22 // schema: { type: 'number' }, 23 // path: '/y', 24 // value: undefined, 25 // message: 'Expected number' 26 // }, { 27 // schema: { type: 'number' }, 28 // path: '/z', 29 // value: undefined, 30 // message: 'Expected number' 31 // }]
Use the Code function to generate assertion functions as strings. This function can be used to generate code that can be written to disk as importable modules. This technique is sometimes referred to as Ahead of Time (AOT) compilation. The following generates code to check a string.
1const C = TypeCompiler.Code(Type.String()) // const C = `return function check(value) { 2 // return ( 3 // (typeof value === 'string') 4 // ) 5 // }`
The TypeBox TypeSystem module provides configurations to use either Json Schema or TypeScript type checking semantics. Configurations made to the TypeSystem module are observed by the TypeCompiler, Value and Error modules.
TypeBox validates using standard Json Schema assertion policies by default. The TypeSystemPolicy module can override some of these to have TypeBox assert values inline with TypeScript static checks. It also provides overrides for certain checking rules related to non-serializable values (such as void) which can be helpful in Json based protocols such as Json Rpc 2.0.
The following overrides are available.
1import { TypeSystemPolicy } from '@sinclair/typebox/system' 2 3// Disallow undefined values for optional properties (default is false) 4// 5// const A: { x?: number } = { x: undefined } - disallowed when enabled 6 7TypeSystemPolicy.ExactOptionalPropertyTypes = true 8 9// Allow arrays to validate as object types (default is false) 10// 11// const A: {} = [] - allowed in TS 12 13TypeSystemPolicy.AllowArrayObject = true 14 15// Allow numeric values to be NaN or + or - Infinity (default is false) 16// 17// const A: number = NaN - allowed in TS 18 19TypeSystemPolicy.AllowNaN = true 20 21// Allow void types to check with undefined and null (default is false) 22// 23// Used to signal void return on Json-Rpc 2.0 protocol 24 25TypeSystemPolicy.AllowNullVoid = true
Error messages in TypeBox can be customized by defining an ErrorFunction. This function allows for the localization of error messages as well as enabling custom error messages for custom types. By default, TypeBox will generate messages using the en-US
locale. To support additional locales, you can replicate the function found in src/errors/function.ts
and create a locale specific translation. The function can then be set via SetErrorFunction.
The following example shows an inline error function that intercepts errors for String, Number and Boolean only. The DefaultErrorFunction is used to return a default error message.
1import { SetErrorFunction, DefaultErrorFunction, ValueErrorType } from '@sinclair/typebox/errors' 2 3SetErrorFunction((error) => { // i18n override 4 switch(error.errorType) { 5 /* en-US */ case ValueErrorType.String: return 'Expected string' 6 /* fr-FR */ case ValueErrorType.Number: return 'Nombre attendu' 7 /* ko-KR */ case ValueErrorType.Boolean: return '예상 부울' 8 /* en-US */ default: return DefaultErrorFunction(error) 9 } 10}) 11const T = Type.Object({ // const T: TObject<{ 12 x: Type.String(), // TString, 13 y: Type.Number(), // TNumber, 14 z: Type.Boolean() // TBoolean 15}) // }> 16 17const E = [...Value.Errors(T, { // const E = [{ 18 x: null, // type: 48, 19 y: null, // schema: { ... }, 20 z: null // path: '/x', 21})] // value: null, 22 // message: 'Expected string' 23 // }, { 24 // type: 34, 25 // schema: { ... }, 26 // path: '/y', 27 // value: null, 28 // message: 'Nombre attendu' 29 // }, { 30 // type: 14, 31 // schema: { ... }, 32 // path: '/z', 33 // value: null, 34 // message: '예상 부울' 35 // }]
TypeBox offers a web based code generation tool that can convert TypeScript types into TypeBox types as well as several other ecosystem libraries.
TypeBox provides a code generation library that can be integrated into toolchains to automate type translation between TypeScript and TypeBox. This library also includes functionality to transform TypeScript types to other ecosystem libraries.
The following is a list of community packages that offer general tooling, extended functionality and framework integration support for TypeBox.
Package | Description |
---|---|
drizzle-typebox | Generates TypeBox types from Drizzle ORM schemas |
elysia | Fast and friendly Bun web framework |
fastify-type-provider-typebox | Fastify TypeBox integration with the Fastify Type Provider |
feathersjs | The API and real-time application framework |
fetch-typebox | Drop-in replacement for fetch that brings easy integration with TypeBox |
h3-typebox | Schema validation utilities for h3 using TypeBox & Ajv |
http-wizard | Type safe http client library for Fastify |
json2typebox | Creating TypeBox code from Json Data |
nominal-typebox | Allows devs to integrate nominal types into TypeBox schemas |
openapi-box | Generate TypeBox types from OpenApi IDL + Http client library |
prismabox | Converts a prisma.schema to typebox schema matching the database models |
schema2typebox | Creating TypeBox code from Json Schemas |
sveltekit-superforms | A comprehensive SvelteKit form library for server and client validation |
ts2typebox | Creating TypeBox code from Typescript types |
typebox-form-parser | Parses form and query data based on TypeBox schemas |
typebox-validators | Advanced validators supporting discriminated and heterogeneous unions |
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.12.0 running on Node 20.10.0.
For additional comparative benchmarks, please refer to typescript-runtime-type-benchmarks.
This benchmark measures compilation performance for varying types.
1┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┐ 2│ (index) │ Iterations │ Ajv │ TypeCompiler │ Performance │ 3├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┤ 4│ Literal_String │ 1000 │ ' 211 ms' │ ' 8 ms' │ ' 26.38 x' │ 5│ Literal_Number │ 1000 │ ' 185 ms' │ ' 5 ms' │ ' 37.00 x' │ 6│ Literal_Boolean │ 1000 │ ' 195 ms' │ ' 4 ms' │ ' 48.75 x' │ 7│ Primitive_Number │ 1000 │ ' 149 ms' │ ' 7 ms' │ ' 21.29 x' │ 8│ Primitive_String │ 1000 │ ' 135 ms' │ ' 5 ms' │ ' 27.00 x' │ 9│ Primitive_String_Pattern │ 1000 │ ' 193 ms' │ ' 10 ms' │ ' 19.30 x' │ 10│ Primitive_Boolean │ 1000 │ ' 152 ms' │ ' 4 ms' │ ' 38.00 x' │ 11│ Primitive_Null │ 1000 │ ' 147 ms' │ ' 4 ms' │ ' 36.75 x' │ 12│ Object_Unconstrained │ 1000 │ ' 1065 ms' │ ' 26 ms' │ ' 40.96 x' │ 13│ Object_Constrained │ 1000 │ ' 1183 ms' │ ' 26 ms' │ ' 45.50 x' │ 14│ Object_Vector3 │ 1000 │ ' 407 ms' │ ' 9 ms' │ ' 45.22 x' │ 15│ Object_Box3D │ 1000 │ ' 1777 ms' │ ' 24 ms' │ ' 74.04 x' │ 16│ Tuple_Primitive │ 1000 │ ' 485 ms' │ ' 11 ms' │ ' 44.09 x' │ 17│ Tuple_Object │ 1000 │ ' 1344 ms' │ ' 17 ms' │ ' 79.06 x' │ 18│ Composite_Intersect │ 1000 │ ' 606 ms' │ ' 14 ms' │ ' 43.29 x' │ 19│ Composite_Union │ 1000 │ ' 522 ms' │ ' 17 ms' │ ' 30.71 x' │ 20│ Math_Vector4 │ 1000 │ ' 851 ms' │ ' 9 ms' │ ' 94.56 x' │ 21│ Math_Matrix4 │ 1000 │ ' 406 ms' │ ' 10 ms' │ ' 40.60 x' │ 22│ Array_Primitive_Number │ 1000 │ ' 367 ms' │ ' 6 ms' │ ' 61.17 x' │ 23│ Array_Primitive_String │ 1000 │ ' 339 ms' │ ' 7 ms' │ ' 48.43 x' │ 24│ Array_Primitive_Boolean │ 1000 │ ' 325 ms' │ ' 5 ms' │ ' 65.00 x' │ 25│ Array_Object_Unconstrained │ 1000 │ ' 1863 ms' │ ' 21 ms' │ ' 88.71 x' │ 26│ Array_Object_Constrained │ 1000 │ ' 1535 ms' │ ' 18 ms' │ ' 85.28 x' │ 27│ Array_Tuple_Primitive │ 1000 │ ' 829 ms' │ ' 14 ms' │ ' 59.21 x' │ 28│ Array_Tuple_Object │ 1000 │ ' 1674 ms' │ ' 14 ms' │ ' 119.57 x' │ 29│ Array_Composite_Intersect │ 1000 │ ' 789 ms' │ ' 13 ms' │ ' 60.69 x' │ 30│ Array_Composite_Union │ 1000 │ ' 822 ms' │ ' 15 ms' │ ' 54.80 x' │ 31│ Array_Math_Vector4 │ 1000 │ ' 1129 ms' │ ' 14 ms' │ ' 80.64 x' │ 32│ Array_Math_Matrix4 │ 1000 │ ' 673 ms' │ ' 9 ms' │ ' 74.78 x' │ 33└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┘
This benchmark measures validation performance for varying types.
1┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐ 2│ (index) │ Iterations │ ValueCheck │ Ajv │ TypeCompiler │ Performance │ 3├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤ 4│ Literal_String │ 1000000 │ ' 17 ms' │ ' 5 ms' │ ' 5 ms' │ ' 1.00 x' │ 5│ Literal_Number │ 1000000 │ ' 14 ms' │ ' 18 ms' │ ' 9 ms' │ ' 2.00 x' │ 6│ Literal_Boolean │ 1000000 │ ' 14 ms' │ ' 20 ms' │ ' 9 ms' │ ' 2.22 x' │ 7│ Primitive_Number │ 1000000 │ ' 17 ms' │ ' 19 ms' │ ' 9 ms' │ ' 2.11 x' │ 8│ Primitive_String │ 1000000 │ ' 17 ms' │ ' 18 ms' │ ' 10 ms' │ ' 1.80 x' │ 9│ Primitive_String_Pattern │ 1000000 │ ' 172 ms' │ ' 46 ms' │ ' 41 ms' │ ' 1.12 x' │ 10│ Primitive_Boolean │ 1000000 │ ' 14 ms' │ ' 19 ms' │ ' 10 ms' │ ' 1.90 x' │ 11│ Primitive_Null │ 1000000 │ ' 16 ms' │ ' 19 ms' │ ' 9 ms' │ ' 2.11 x' │ 12│ Object_Unconstrained │ 1000000 │ ' 437 ms' │ ' 28 ms' │ ' 14 ms' │ ' 2.00 x' │ 13│ Object_Constrained │ 1000000 │ ' 653 ms' │ ' 46 ms' │ ' 37 ms' │ ' 1.24 x' │ 14│ Object_Vector3 │ 1000000 │ ' 201 ms' │ ' 22 ms' │ ' 12 ms' │ ' 1.83 x' │ 15│ Object_Box3D │ 1000000 │ ' 961 ms' │ ' 37 ms' │ ' 19 ms' │ ' 1.95 x' │ 16│ Object_Recursive │ 1000000 │ ' 3715 ms' │ ' 363 ms' │ ' 174 ms' │ ' 2.09 x' │ 17│ Tuple_Primitive │ 1000000 │ ' 107 ms' │ ' 23 ms' │ ' 11 ms' │ ' 2.09 x' │ 18│ Tuple_Object │ 1000000 │ ' 375 ms' │ ' 28 ms' │ ' 15 ms' │ ' 1.87 x' │ 19│ Composite_Intersect │ 1000000 │ ' 377 ms' │ ' 22 ms' │ ' 12 ms' │ ' 1.83 x' │ 20│ Composite_Union │ 1000000 │ ' 337 ms' │ ' 30 ms' │ ' 17 ms' │ ' 1.76 x' │ 21│ Math_Vector4 │ 1000000 │ ' 137 ms' │ ' 23 ms' │ ' 11 ms' │ ' 2.09 x' │ 22│ Math_Matrix4 │ 1000000 │ ' 576 ms' │ ' 37 ms' │ ' 28 ms' │ ' 1.32 x' │ 23│ Array_Primitive_Number │ 1000000 │ ' 145 ms' │ ' 23 ms' │ ' 12 ms' │ ' 1.92 x' │ 24│ Array_Primitive_String │ 1000000 │ ' 152 ms' │ ' 22 ms' │ ' 13 ms' │ ' 1.69 x' │ 25│ Array_Primitive_Boolean │ 1000000 │ ' 131 ms' │ ' 20 ms' │ ' 13 ms' │ ' 1.54 x' │ 26│ Array_Object_Unconstrained │ 1000000 │ ' 2821 ms' │ ' 62 ms' │ ' 45 ms' │ ' 1.38 x' │ 27│ Array_Object_Constrained │ 1000000 │ ' 2958 ms' │ ' 119 ms' │ ' 134 ms' │ ' 0.89 x' │ 28│ Array_Object_Recursive │ 1000000 │ ' 14695 ms' │ ' 1621 ms' │ ' 635 ms' │ ' 2.55 x' │ 29│ Array_Tuple_Primitive │ 1000000 │ ' 478 ms' │ ' 35 ms' │ ' 28 ms' │ ' 1.25 x' │ 30│ Array_Tuple_Object │ 1000000 │ ' 1623 ms' │ ' 63 ms' │ ' 48 ms' │ ' 1.31 x' │ 31│ Array_Composite_Intersect │ 1000000 │ ' 1582 ms' │ ' 43 ms' │ ' 30 ms' │ ' 1.43 x' │ 32│ Array_Composite_Union │ 1000000 │ ' 1331 ms' │ ' 76 ms' │ ' 40 ms' │ ' 1.90 x' │ 33│ Array_Math_Vector4 │ 1000000 │ ' 564 ms' │ ' 38 ms' │ ' 24 ms' │ ' 1.58 x' │ 34│ Array_Math_Matrix4 │ 1000000 │ ' 2382 ms' │ ' 111 ms' │ ' 83 ms' │ ' 1.34 x' │ 35└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘
The following table lists esbuild compiled and minified sizes for each TypeBox module.
1┌──────────────────────┬────────────┬────────────┬─────────────┐ 2│ (index) │ Compiled │ Minified │ Compression │ 3├──────────────────────┼────────────┼────────────┼─────────────┤ 4│ typebox/compiler │ '122.4 kb' │ ' 53.4 kb' │ '2.29 x' │ 5│ typebox/errors │ ' 67.6 kb' │ ' 29.6 kb' │ '2.28 x' │ 6│ typebox/syntax │ '132.9 kb' │ ' 54.2 kb' │ '2.45 x' │ 7│ typebox/system │ ' 7.4 kb' │ ' 3.2 kb' │ '2.33 x' │ 8│ typebox/value │ '150.1 kb' │ ' 62.2 kb' │ '2.41 x' │ 9│ typebox │ '106.8 kb' │ ' 43.2 kb' │ '2.47 x' │ 10└──────────────────────┴────────────┴────────────┴─────────────┘
TypeBox is open to community contribution. Please ensure you submit an open issue before submitting your pull request. The TypeBox project prefers open community discussion before accepting new features.
No vulnerabilities found.
Reason
30 commit(s) and 25 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 6/30 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More