@sinclair/typebox 0.28.19 → 0.28.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md CHANGED
@@ -1,1563 +1,1563 @@
1
- <div align='center'>
2
-
3
- <h1>TypeBox</h1>
4
-
5
- <p>JSON Schema Type Builder with Static Type Resolution for TypeScript</p>
6
-
7
- <img src="https://github.com/sinclairzx81/typebox/blob/master/typebox.png?raw=true" />
8
-
9
- <br />
10
- <br />
11
-
12
- [![npm version](https://badge.fury.io/js/%40sinclair%2Ftypebox.svg)](https://badge.fury.io/js/%40sinclair%2Ftypebox)
13
- [![Downloads](https://img.shields.io/npm/dm/%40sinclair%2Ftypebox.svg)](https://www.npmjs.com/package/%40sinclair%2Ftypebox)
14
- [![GitHub CI](https://github.com/sinclairzx81/typebox/workflows/GitHub%20CI/badge.svg)](https://github.com/sinclairzx81/typebox/actions)
15
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
16
-
17
- </div>
18
-
19
- <a name="Install"></a>
20
-
21
- ## Install
22
-
23
- #### Npm
24
- ```bash
25
- $ npm install @sinclair/typebox --save
26
- ```
27
-
28
- #### Deno
29
- ```typescript
30
- import { Static, Type } from 'npm:@sinclair/typebox'
31
- ```
32
-
33
- #### Esm
34
-
35
- ```typescript
36
- import { Static, Type } from 'https://esm.sh/@sinclair/typebox'
37
- ```
38
-
39
- ## Example
40
-
41
- ```typescript
42
- import { Static, Type } from '@sinclair/typebox'
43
-
44
- const T = Type.Object({ // const T = {
45
- x: Type.Number(), // type: 'object',
46
- y: Type.Number(), // required: ['x', 'y', 'z'],
47
- z: Type.Number() // properties: {
48
- }) // x: { type: 'number' },
49
- // y: { type: 'number' },
50
- // z: { type: 'number' }
51
- // }
52
- // }
53
-
54
- type T = Static<typeof T> // type T = {
55
- // x: number,
56
- // y: number,
57
- // z: number
58
- // }
59
- ```
60
-
61
-
62
- <a name="Overview"></a>
63
-
64
- ## Overview
65
-
66
- TypeBox is a runtime type builder that creates 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 assertion 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.
67
-
68
- 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 or RPC services to help validate data received over the wire.
69
-
70
- License MIT
71
-
72
- ## Contents
73
- - [Install](#install)
74
- - [Overview](#overview)
75
- - [Usage](#usage)
76
- - [Types](#types)
77
- - [Standard](#types-standard)
78
- - [Extended](#types-extended)
79
- - [Modifiers](#types-modifiers)
80
- - [Options](#types-options)
81
- - [Generics](#types-generics)
82
- - [References](#types-references)
83
- - [Recursive](#types-recursive)
84
- - [Conditional](#types-conditional)
85
- - [Template Literal](#types-template-literal)
86
- - [Indexed](#types-indexed)
87
- - [Rest](#types-rest)
88
- - [Guards](#types-guards)
89
- - [Unsafe](#types-unsafe)
90
- - [Strict](#types-strict)
91
- - [Values](#values)
92
- - [Create](#values-create)
93
- - [Clone](#values-clone)
94
- - [Check](#values-check)
95
- - [Convert](#values-convert)
96
- - [Cast](#values-cast)
97
- - [Equal](#values-equal)
98
- - [Hash](#values-hash)
99
- - [Diff](#values-diff)
100
- - [Patch](#values-patch)
101
- - [Errors](#values-errors)
102
- - [Mutate](#values-mutate)
103
- - [Pointer](#values-pointer)
104
- - [TypeCheck](#typecheck)
105
- - [Ajv](#typecheck-ajv)
106
- - [TypeCompiler](#typecheck-typecompiler)
107
- - [TypeSystem](#typesystem)
108
- - [Types](#typesystem-types)
109
- - [Formats](#typesystem-formats)
110
- - [Policies](#typesystem-policies)
111
- - [Workbench](#workbench)
112
- - [Ecosystem](#ecosystem)
113
- - [Benchmark](#benchmark)
114
- - [Compile](#benchmark-compile)
115
- - [Validate](#benchmark-validate)
116
- - [Compression](#benchmark-compression)
117
- - [Contribute](#contribute)
118
-
119
- <a name="usage"></a>
120
-
121
- ## Usage
122
-
123
- The following shows general usage.
124
-
125
- ```typescript
126
- import { Static, Type } from '@sinclair/typebox'
127
-
128
- //--------------------------------------------------------------------------------------------
129
- //
130
- // Let's say you have the following type ...
131
- //
132
- //--------------------------------------------------------------------------------------------
133
-
134
- type T = {
135
- id: string,
136
- name: string,
137
- timestamp: number
138
- }
139
-
140
- //--------------------------------------------------------------------------------------------
141
- //
142
- // ... you can express this type in the following way.
143
- //
144
- //--------------------------------------------------------------------------------------------
145
-
146
- const T = Type.Object({ // const T = {
147
- id: Type.String(), // type: 'object',
148
- name: Type.String(), // properties: {
149
- timestamp: Type.Integer() // id: {
150
- }) // type: 'string'
151
- // },
152
- // name: {
153
- // type: 'string'
154
- // },
155
- // timestamp: {
156
- // type: 'integer'
157
- // }
158
- // },
159
- // required: [
160
- // 'id',
161
- // 'name',
162
- // 'timestamp'
163
- // ]
164
- // }
165
-
166
- //--------------------------------------------------------------------------------------------
167
- //
168
- // ... then infer back to the original static type this way.
169
- //
170
- //--------------------------------------------------------------------------------------------
171
-
172
- type T = Static<typeof T> // type T = {
173
- // id: string,
174
- // name: string,
175
- // timestamp: number
176
- // }
177
-
178
- //--------------------------------------------------------------------------------------------
179
- //
180
- // ... then use the type both as JSON schema and as a TypeScript type.
181
- //
182
- //--------------------------------------------------------------------------------------------
183
-
184
- import { Value } from '@sinclair/typebox/value'
185
-
186
- function receive(value: T) { // ... as a Static Type
187
-
188
- if(Value.Check(T, value)) { // ... as a JSON Schema
189
-
190
- // ok...
191
- }
192
- }
193
- ```
194
-
195
- <a name='types'></a>
196
-
197
- ## Types
198
-
199
- TypeBox types are JSON schema fragments that can be composed into more complex types. Each fragment is structured such that a JSON schema compliant validator can runtime assert a value the same way TypeScript will statically assert a type. TypeBox provides a set of Standard types which are used create JSON schema compliant schematics as well as an Extended type set used to create schematics for constructs native to JavaScript.
200
-
201
- <a name='types-standard'></a>
202
-
203
- ### Standard Types
204
-
205
- The following table lists the Standard TypeBox types. These types are fully compatible with the JSON Schema Draft 6 specification.
206
-
207
- ```typescript
208
- ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
209
- │ TypeBox │ TypeScript │ JSON Schema │
210
- │ │ │ │
211
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
212
- │ const T = Type.Any() │ type T = any │ const T = { } │
213
- │ │ │ │
214
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
215
- │ const T = Type.Unknown() │ type T = unknown │ const T = { } │
216
- │ │ │ │
217
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
218
- │ const T = Type.String() │ type T = string │ const T = { │
219
- │ │ │ type: 'string' │
220
- │ │ │ } │
221
- │ │ │ │
222
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
223
- │ const T = Type.Number() │ type T = number │ const T = { │
224
- │ │ │ type: 'number' │
225
- │ │ │ } │
226
- │ │ │ │
227
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
228
- │ const T = Type.Integer() │ type T = number │ const T = { │
229
- │ │ │ type: 'integer' │
230
- │ │ │ } │
231
- │ │ │ │
232
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
233
- │ const T = Type.Boolean() │ type T = boolean │ const T = { │
234
- │ │ │ type: 'boolean' │
235
- │ │ │ } │
236
- │ │ │ │
237
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
238
- │ const T = Type.Null() │ type T = null │ const T = { │
239
- │ │ │ type: 'null' │
240
- │ │ │ } │
241
- │ │ │ │
242
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
243
- │ const T = Type.Literal(42) │ type T = 42 │ const T = { │
244
- │ │ │ const: 42, │
245
- │ │ │ type: 'number' │
246
- │ │ │ } │
247
- │ │ │ │
248
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
249
- │ const T = Type.Array( │ type T = number[] │ const T = { │
250
- │ Type.Number() │ │ type: 'array', │
251
- │ ) │ │ items: { │
252
- │ │ │ type: 'number' │
253
- │ │ │ } │
254
- │ │ │ } │
255
- │ │ │ │
256
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
257
- │ const T = Type.Object({ │ type T = { │ const T = { │
258
- │ x: Type.Number(), │ x: number, │ type: 'object', │
259
- │ y: Type.Number() │ y: number │ required: ['x', 'y'], │
260
- │ }) │ } │ properties: { │
261
- │ │ │ x: { │
262
- │ │ │ type: 'number' │
263
- │ │ │ }, │
264
- │ │ │ y: { │
265
- │ │ │ type: 'number' │
266
- │ │ │ } │
267
- │ │ │ } │
268
- │ │ │ } │
269
- │ │ │ │
270
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
271
- │ const T = Type.Tuple([ │ type T = [number, number] │ const T = { │
272
- │ Type.Number(), │ │ type: 'array', │
273
- │ Type.Number() │ │ items: [{ │
274
- │ ]) │ │ type: 'number' │
275
- │ │ │ }, { │
276
- │ │ │ type: 'number' │
277
- │ │ │ }], │
278
- │ │ │ additionalItems: false, │
279
- │ │ │ minItems: 2, │
280
- │ │ │ maxItems: 2 │
281
- │ │ │ } │
282
- │ │ │ │
283
- │ │ │ │
284
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
285
- │ enum Foo { │ enum Foo { │ const T = { │
286
- │ A, │ A, │ anyOf: [{ │
287
- │ B │ B │ type: 'number', │
288
- │ } │ } │ const: 0 │
289
- │ │ │ }, { │
290
- │ const T = Type.Enum(Foo) │ type T = Foo │ type: 'number', │
291
- │ │ │ const: 1 │
292
- │ │ │ }] │
293
- │ │ │ } │
294
- │ │ │ │
295
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
296
- │ const T = Type.KeyOf( │ type T = keyof { │ const T = { │
297
- │ Type.Object({ │ x: number, │ anyOf: [{ │
298
- │ x: Type.Number(), │ y: number │ type: 'string', │
299
- │ y: Type.Number() │ } │ const: 'x' │
300
- │ }) │ │ }, { │
301
- │ ) │ │ type: 'string', │
302
- │ │ │ const: 'y' │
303
- │ │ │ }] │
304
- │ │ │ } │
305
- │ │ │ │
306
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
307
- │ const T = Type.Union([ │ type T = string | number │ const T = { │
308
- │ Type.String(), │ │ anyOf: [{ │
309
- │ Type.Number() │ │ type: 'string' │
310
- │ ]) │ │ }, { │
311
- │ │ │ type: 'number' │
312
- │ │ │ }] │
313
- │ │ │ } │
314
- │ │ │ │
315
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
316
- │ const T = Type.Intersect([ │ type T = { │ const T = { │
317
- │ Type.Object({ │ x: number │ allOf: [{ │
318
- │ x: Type.Number() │ } & { │ type: 'object', │
319
- │ }), │ y: number │ required: ['x'], │
320
- │ Type.Object({ │ } │ properties: { │
321
- │ y: Type.Number() │ │ x: { │
322
- │ ]) │ │ type: 'number' │
323
- │ ]) │ │ } │
324
- │ │ │ } │
325
- │ │ │ }, { │
326
- │ │ │ type: 'object', |
327
- │ │ │ required: ['y'], │
328
- │ │ │ properties: { │
329
- │ │ │ y: { │
330
- │ │ │ type: 'number' │
331
- │ │ │ } │
332
- │ │ │ } │
333
- │ │ │ }] │
334
- │ │ │ } │
335
- │ │ │ │
336
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
337
- │ const T = Type.Composite([ │ type I = { │ const T = { │
338
- │ Type.Object({ │ x: number │ type: 'object', │
339
- │ x: Type.Number() │ } & { │ required: ['x', 'y'], │
340
- │ }), │ y: number │ properties: { │
341
- │ Type.Object({ │ } │ x: { │
342
- │ y: Type.Number() │ │ type: 'number' │
343
- │ }) │ type T = { │ }, │
344
- │ ]) │ [K in keyof I]: I[K] │ y: { │
345
- │ │ } │ type: 'number' │
346
- │ │ │ } │
347
- │ │ │ } │
348
- │ │ │ } │
349
- │ │ │ │
350
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
351
- │ const T = Type.Never() │ type T = never │ const T = { │
352
- │ │ │ not: {} │
353
- │ │ │ } │
354
- │ │ │ │
355
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
356
- │ const T = Type.Not( | type T = string │ const T = { │
357
- | Type.Union([ │ │ allOf: [{ │
358
- │ Type.Literal('x'), │ │ not: { │
359
- │ Type.Literal('y'), │ │ anyOf: [ │
360
- │ Type.Literal('z') │ │ { const: 'x' }, │
361
- │ ]), │ │ { const: 'y' }, │
362
- │ Type.String() │ │ { const: 'z' } │
363
- │ ) │ │ ] │
364
- │ │ │ } │
365
- │ │ │ }, { │
366
- │ │ │ type: 'string' │
367
- │ │ │ }] │
368
- │ │ │ } │
369
- │ │ │ │
370
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
371
- │ const T = Type.Extends( │ type T = │ const T = { │
372
- │ Type.String(), │ string extends number │ const: false, │
373
- │ Type.Number(), │ true : false │ type: 'boolean' │
374
- │ Type.Literal(true), │ │ } │
375
- │ Type.Literal(false) │ │ │
376
- │ ) │ │ │
377
- │ │ │ │
378
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
379
- │ const T = Type.Extract( │ type T = Extract< │ const T = { │
380
- │ Type.Union([ │ string | number, │ type: 'string' │
381
- │ Type.String(), │ string │ } │
382
- │ Type.Number(), │ > │ │
383
- │ ]), │ │ │
384
- │ Type.String() │ │ │
385
- │ ) │ │ │
386
- │ │ │ │
387
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
388
- │ const T = Type.Exclude( │ type T = Exclude< │ const T = { │
389
- │ Type.Union([ │ string | number, │ type: 'number' │
390
- │ Type.String(), │ string │ } │
391
- │ Type.Number(), │ > │ │
392
- │ ]), │ │ │
393
- │ Type.String() │ │ │
394
- │ ) │ │ │
395
- │ │ │ │
396
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
397
- │ const U = Type.Union([ │ type U = 'open' | 'close' │ const T = { │
398
- │ Type.Literal('open'), │ │ type: 'string', │
399
- │ Type.Literal('close') │ type T = `on${U}` │ pattern: '^on(open|close)$' │
400
- │ ]) │ │ } │
401
- │ │ │ │
402
- │ const T = Type │ │ │
403
- │ .TemplateLiteral([ │ │ │
404
- │ Type.Literal('on'), │ │ │
405
- │ U │ │ │
406
- │ ]) │ │ │
407
- │ │ │ │
408
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
409
- │ const T = Type.Record( │ type T = Record< │ const T = { │
410
- │ Type.String(), │ string, │ type: 'object', │
411
- │ Type.Number() │ number │ patternProperties: { │
412
- │ ) │ > │ '^.*$': { │
413
- │ │ │ type: 'number' │
414
- │ │ │ } │
415
- │ │ │ } │
416
- │ │ │ } │
417
- │ │ │ │
418
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
419
- │ const T = Type.Partial( │ type T = Partial<{ │ const T = { │
420
- │ Type.Object({ │ x: number, │ type: 'object', │
421
- │ x: Type.Number(), │ y: number │ properties: { │
422
- │ y: Type.Number() | }> │ x: { │
423
- │ }) │ │ type: 'number' │
424
- │ ) │ │ }, │
425
- │ │ │ y: { │
426
- │ │ │ type: 'number' │
427
- │ │ │ } │
428
- │ │ │ } │
429
- │ │ │ } │
430
- │ │ │ │
431
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
432
- │ const T = Type.Required( │ type T = Required<{ │ const T = { │
433
- │ Type.Object({ │ x?: number, │ type: 'object', │
434
- │ x: Type.Optional( │ y?: number │ required: ['x', 'y'], │
435
- │ Type.Number() | }> │ properties: { │
436
- │ ), │ │ x: { │
437
- │ y: Type.Optional( │ │ type: 'number' │
438
- │ Type.Number() │ │ }, │
439
- │ ) │ │ y: { │
440
- │ }) │ │ type: 'number' │
441
- │ ) │ │ } │
442
- │ │ │ } │
443
- │ │ │ } │
444
- │ │ │ │
445
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
446
- │ const T = Type.Pick( │ type T = Pick<{ │ const T = { │
447
- │ Type.Object({ │ x: number, │ type: 'object', │
448
- │ x: Type.Number(), │ y: number │ required: ['x'], │
449
- │ y: Type.Number() │ }, 'x'> │ properties: { │
450
- │ }), ['x'] | │ x: { │
451
- │ ) │ │ type: 'number' │
452
- │ │ │ } │
453
- │ │ │ } │
454
- │ │ │ } │
455
- │ │ │ │
456
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
457
- │ const T = Type.Omit( │ type T = Omit<{ │ const T = { │
458
- │ Type.Object({ │ x: number, │ type: 'object', │
459
- │ x: Type.Number(), │ y: number │ required: ['y'], │
460
- │ y: Type.Number() │ }, 'x'> │ properties: { │
461
- │ }), ['x'] | │ y: { │
462
- │ ) │ │ type: 'number' │
463
- │ │ │ } │
464
- │ │ │ } │
465
- │ │ │ } │
466
- │ │ │ │
467
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
468
- │ const T = Type.Index( │ type T = { │ const T = { │
469
- │ Type.Object({ │ x: number, │ type: 'number' │
470
- │ x: Type.Number(), │ y: string │ } │
471
- │ y: Type.String() │ }['x'] │ │
472
- │ }), ['x'] │ │ │
473
- │ ) │ │ │
474
- │ │ │ │
475
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
476
- │ const A = Type.Tuple([ │ type A = [0, 1] │ const T = { │
477
- │ Type.Literal(0), │ type B = [2, 3] │ type: 'array', │
478
- │ Type.Literal(1) │ type T = [...A, ...B] │ items: [ │
479
- │ ]) │ │ { const: 0 }, │
480
- │ const B = Type.Tuple([ │ │ { const: 1 }, │
481
- | Type.Literal(2), │ │ { const: 2 }, │
482
- | Type.Literal(3) │ │ { const: 3 } │
483
- │ ]) │ │ ], │
484
- │ const T = Type.Tuple([ │ │ additionalItems: false, │
485
- | ...Type.Rest(A), │ │ minItems: 4, │
486
- | ...Type.Rest(B) │ │ maxItems: 4 │
487
- │ ]) │ │ } │
488
- │ │ │ │
489
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
490
- │ const T = Type.Object({ │ type T = { │ const R = { │
491
- │ x: Type.Number(), │ x: number, │ $ref: 'T' │
492
- │ y: Type.Number() │ y: number │ } │
493
- │ }, { $id: 'T' }) | } │ │
494
- │ │ │ │
495
- │ const R = Type.Ref(T) │ type R = T │ │
496
- │ │ │ │
497
- │ │ │ │
498
- │ │ │ │
499
- │ │ │ │
500
- └────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
501
- ```
502
-
503
- <a name='types-extended'></a>
504
-
505
- ### Extended Types
506
-
507
- TypeBox provides several extended types that can be used to produce schematics for common JavaScript constructs. These types can not 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 table lists the supported types.
508
-
509
- ```typescript
510
- ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
511
- │ TypeBox │ TypeScript │ Extended Schema │
512
- │ │ │ │
513
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
514
- │ const T = Type.Constructor([ │ type T = new ( │ const T = { │
515
- │ Type.String(), │ arg0: string, │ type: 'object', │
516
- │ Type.Number() │ arg1: number │ instanceOf: 'Constructor', │
517
- │ ], Type.Boolean()) │ ) => boolean │ parameters: [{ │
518
- │ │ │ type: 'string' │
519
- │ │ │ }, { │
520
- │ │ │ type: 'number' │
521
- │ │ │ }], │
522
- │ │ │ return: { │
523
- │ │ │ type: 'boolean' │
524
- │ │ │ } │
525
- │ │ │ } │
526
- │ │ │ │
527
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
528
- │ const T = Type.Function([ │ type T = ( │ const T = { │
529
- | Type.String(), │ arg0: string, │ type : 'object', │
530
- │ Type.Number() │ arg1: number │ instanceOf: 'Function', │
531
- │ ], Type.Boolean()) │ ) => boolean │ parameters: [{ │
532
- │ │ │ type: 'string' │
533
- │ │ │ }, { │
534
- │ │ │ type: 'number' │
535
- │ │ │ }], │
536
- │ │ │ return: { │
537
- │ │ │ type: 'boolean' │
538
- │ │ │ } │
539
- │ │ │ } │
540
- │ │ │ │
541
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
542
- │ const T = Type.Promise( │ type T = Promise<string> │ const T = { │
543
- │ Type.String() │ │ type: 'object', │
544
- │ ) │ │ instanceOf: 'Promise', │
545
- │ │ │ item: { │
546
- │ │ │ type: 'string' │
547
- │ │ │ } │
548
- │ │ │ } │
549
- │ │ │ │
550
- │ │ │ │
551
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
552
- │ const T = Type.Uint8Array() │ type T = Uint8Array │ const T = { │
553
- │ │ │ type: 'object', │
554
- │ │ │ instanceOf: 'Uint8Array' │
555
- │ │ │ } │
556
- │ │ │ │
557
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
558
- │ const T = Type.Date() │ type T = Date │ const T = { │
559
- │ │ │ type: 'object', │
560
- │ │ │ instanceOf: 'Date' │
561
- │ │ │ } │
562
- │ │ │ │
563
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
564
- │ const T = Type.Undefined() │ type T = undefined │ const T = { │
565
- │ │ │ type: 'null', │
566
- │ │ │ typeOf: 'Undefined' │
567
- │ │ │ } │
568
- │ │ │ │
569
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
570
- │ const T = Type.RegEx(/foo/) │ type T = string │ const T = { │
571
- │ │ │ type: 'string', │
572
- │ │ │ pattern: 'foo' │
573
- │ │ │ } │
574
- │ │ │ │
575
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
576
- │ const T = Type.Symbol() │ type T = symbol │ const T = { │
577
- │ │ │ type: 'null', │
578
- │ │ │ typeOf: 'Symbol' │
579
- │ │ │ } │
580
- │ │ │ │
581
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
582
- │ const T = Type.BigInt() │ type T = bigint │ const T = { │
583
- │ │ │ type: 'null', │
584
- │ │ │ typeOf: 'BigInt' │
585
- │ │ │ } │
586
- │ │ │ │
587
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
588
- │ const T = Type.Void() │ type T = void │ const T = { │
589
- │ │ │ type: 'null' │
590
- │ │ │ typeOf: 'Void' │
591
- │ │ │ } │
592
- │ │ │ │
593
- └────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
594
- ```
595
-
596
- <a name='types-modifiers'></a>
597
-
598
- ### Modifiers
599
-
600
- TypeBox provides modifiers that allow schema properties to be statically inferred as `readonly` or `optional`. The following table shows the supported modifiers and how they map between TypeScript and JSON Schema.
601
-
602
- ```typescript
603
- ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
604
- │ TypeBox │ TypeScript │ JSON Schema │
605
- │ │ │ │
606
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
607
- │ const T = Type.Object({ │ type T = { │ const T = { │
608
- │ name: Type.Optional( │ name?: string │ type: 'object', │
609
- │ Type.String() │ } │ properties: { │
610
- │ ) │ │ name: { │
611
- │ }) │ │ type: 'string' │
612
- │ │ │ } │
613
- │ │ │ } │
614
- │ │ │ } │
615
- │ │ │ │
616
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
617
- │ const T = Type.Object({ │ type T = { │ const T = { │
618
- │ name: Type.Readonly( │ readonly name: string │ type: 'object', │
619
- │ Type.String() │ } │ properties: { │
620
- │ ) │ │ name: { │
621
- │ }) │ │ type: 'string' │
622
- │ │ │ } │
623
- │ │ │ }, │
624
- │ │ │ required: ['name'] │
625
- │ │ │ } │
626
- │ │ │ │
627
- ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
628
- │ const T = Type.Object({ │ type T = { │ const T = { │
629
- │ name: Type.ReadonlyOptional( │ readonly name?: string │ type: 'object', │
630
- │ Type.String() │ } │ properties: { │
631
- │ ) │ │ name: { │
632
- │ }) │ │ type: 'string' │
633
- │ │ │ } │
634
- │ │ │ } │
635
- │ │ │ } │
636
- │ │ │ │
637
- └────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
638
- ```
639
-
640
- <a name='types-options'></a>
641
-
642
- ### Options
643
-
644
- You can pass JSON Schema options on the last argument of any type. Option hints specific to each type are provided for convenience.
645
-
646
- ```typescript
647
- // String must be an email
648
- const T = Type.String({ // const T = {
649
- format: 'email' // type: 'string',
650
- }) // format: 'email'
651
- // }
652
-
653
- // Mumber must be a multiple of 2
654
- const T = Type.Number({ // const T = {
655
- multipleOf: 2 // type: 'number',
656
- }) // multipleOf: 2
657
- // }
658
-
659
- // Array must have at least 5 integer values
660
- const T = Type.Array(Type.Integer(), { // const T = {
661
- minItems: 5 // type: 'array',
662
- }) // minItems: 5,
663
- // items: {
664
- // type: 'integer'
665
- // }
666
- // }
667
-
668
- ```
669
-
670
- <a name='types-generics'></a>
671
-
672
- ### Generic Types
673
-
674
- Generic types can be created with generic functions constrained to type `TSchema`. The following creates a generic `Vector<T>` type.
675
-
676
- ```typescript
677
- import { Type, Static, TSchema } from '@sinclair/typebox'
678
-
679
- const Vector = <T extends TSchema>(t: T) => Type.Object({ x: t, y: t, z: t })
680
-
681
- const NumberVector = Vector(Type.Number()) // const NumberVector = {
682
- // type: 'object',
683
- // required: ['x', 'y', 'z'],
684
- // properties: {
685
- // x: { type: 'number' },
686
- // y: { type: 'number' },
687
- // z: { type: 'number' }
688
- // }
689
- // }
690
-
691
- type NumberVector = Static<typeof NumberVector> // type NumberVector = {
692
- // x: number,
693
- // y: number,
694
- // z: number
695
- // }
696
-
697
- const BooleanVector = Vector(Type.Boolean()) // const BooleanVector = {
698
- // type: 'object',
699
- // required: ['x', 'y', 'z'],
700
- // properties: {
701
- // x: { type: 'boolean' },
702
- // y: { type: 'boolean' },
703
- // z: { type: 'boolean' }
704
- // }
705
- // }
706
-
707
- type BooleanVector = Static<typeof BooleanVector> // type BooleanVector = {
708
- // x: boolean,
709
- // y: boolean,
710
- // z: boolean
711
- // }
712
- ```
713
-
714
- The following creates a generic `Nullable<T>` type.
715
-
716
- ```typescript
717
- const Nullable = <T extends TSchema>(schema: T) => Type.Union([schema, Type.Null()])
718
-
719
- const T = Nullable(Type.String()) // const T = {
720
- // anyOf: [
721
- // { type: 'string' },
722
- // { type: 'null' }
723
- // ]
724
- // }
725
-
726
- type T = Static<typeof T> // type T = string | null
727
- ```
728
-
729
- <a name='types-references'></a>
730
-
731
- ### Reference Types
732
-
733
- Reference types are supported with `Type.Ref`. The target type must specify a valid `$id`.
734
-
735
- ```typescript
736
- const T = Type.String({ $id: 'T' }) // const T = {
737
- // $id: 'T',
738
- // type: 'string'
739
- // }
740
-
741
- const R = Type.Ref(T) // const R = {
742
- // $ref: 'T'
743
- // }
744
- ```
745
-
746
- <a name='types-recursive'></a>
747
-
748
- ### Recursive Types
749
-
750
- Recursive types are supported with `Type.Recursive`
751
-
752
- ```typescript
753
- const Node = Type.Recursive(Node => Type.Object({ // const Node = {
754
- id: Type.String(), // $id: 'Node',
755
- nodes: Type.Array(Node) // type: 'object',
756
- }), { $id: 'Node' }) // properties: {
757
- // id: {
758
- // type: 'string'
759
- // },
760
- // nodes: {
761
- // type: 'array',
762
- // items: {
763
- // $ref: 'Node'
764
- // }
765
- // }
766
- // },
767
- // required: [
768
- // 'id',
769
- // 'nodes'
770
- // ]
771
- // }
772
-
773
- type Node = Static<typeof Node> // type Node = {
774
- // id: string
775
- // nodes: Node[]
776
- // }
777
-
778
- function test(node: Node) {
779
- const id = node.nodes[0].nodes[0].id // id is string
780
- }
781
- ```
782
-
783
- <a name='types-conditional'></a>
784
-
785
- ### Conditional Types
786
-
787
- Conditional types are supported with `Type.Extends`, `Type.Exclude` and `Type.Extract`
788
-
789
- ```typescript
790
- // TypeScript
791
-
792
- type T0 = string extends number ? true : false // type T0 = false
793
-
794
- type T1 = Extract<string | number, number> // type T1 = number
795
-
796
- type T2 = Exclude<string | number, number> // type T2 = string
797
-
798
- // TypeBox
799
-
800
- const T0 = Type.Extends(Type.String(), Type.Number(), Type.Literal(true), Type.Literal(false))
801
-
802
- const T1 = Type.Extract(Type.Union([Type.String(), Type.Number()]), Type.Number())
803
-
804
- const T2 = Type.Exclude(Type.Union([Type.String(), Type.Number()]), Type.Number())
805
-
806
-
807
- type T0 = Static<typeof T0> // type T0 = false
808
-
809
- type T1 = Static<typeof T1> // type T1 = number
810
-
811
- type T2 = Static<typeof T2> // type T2 = string
812
- ```
813
-
814
- <a name='types-template-literal'></a>
815
-
816
- ### Template Literal Types
817
-
818
- TypeBox supports Template Literal types using `Type.TemplateLiteral`. These types can be created using a simple template DSL syntax, however more complex template literals can be created by passing an array of literal and union types. The examples below show the template DSL syntax.
819
-
820
- ```typescript
821
- // TypeScript
822
-
823
- type P = `/post/${string}/user/${number}` // type P = `/post/${string}/user/${number}`
824
-
825
- type T = `option${'A'|'B'}` // type T = 'optionA' | 'optionB'
826
-
827
- type R = Record<T, string> // type R = {
828
- // optionA: string
829
- // optionB: string
830
- // }
831
-
832
- // TypeBox
833
-
834
- const P = Type.TemplateLiteral('/post/${string}/user/${number}')
835
-
836
- // const P = {
837
- // type: 'string',
838
- // pattern: '^/post/(.*)/user/(0|[1-9][0-9]*)$'
839
- // }
840
-
841
- const T = Type.TemplateLiteral('option${A|B}') // const T = {
842
- // pattern: '^option(A|B)$',
843
- // type: 'string'
844
- // }
845
-
846
- const R = Type.Record(T, Type.String()) // const R = {
847
- // type: 'object',
848
- // required: ['optionA', 'optionB'],
849
- // properties: {
850
- // optionA: {
851
- // type: 'string'
852
- // },
853
- // optionB: {
854
- // type: 'string'
855
- // }
856
- // }
857
- // }
858
- ```
859
-
860
- <a name='types-indexed'></a>
861
-
862
- ### Indexed Access Types
863
-
864
- TypeBox supports Indexed Access types using `Type.Index`. This feature provides a consistent way to access property types without having to extract them from the underlying schema representation. Indexed accessors are supported for object and tuples, as well as nested union and intersect types.
865
-
866
- ```typescript
867
- const T = Type.Object({ // const T = {
868
- x: Type.Number(), // type: 'object',
869
- y: Type.String(), // required: ['x', 'y', 'z'],
870
- z: Type.Boolean() // properties: {
871
- }) // x: { type: 'number' },
872
- // y: { type: 'string' },
873
- // z: { type: 'string' }
874
- // }
875
- // }
876
-
877
- const A = Type.Index(T, ['x']) // const A = { type: 'number' }
878
-
879
- const B = Type.Index(T, ['x', 'y']) // const B = {
880
- // anyOf: [
881
- // { type: 'number' },
882
- // { type: 'string' }
883
- // ]
884
- // }
885
-
886
- const C = Type.Index(T, Type.KeyOf(T)) // const C = {
887
- // anyOf: [
888
- // { type: 'number' },
889
- // { type: 'string' },
890
- // { type: 'boolean' }
891
- // ]
892
- // }
893
- ```
894
-
895
- <a name='types-rest'></a>
896
-
897
- ### Rest Types
898
-
899
- Rest parameters are supported with `Type.Rest`. This function is used to extract interior type elements from tuples which enables them to compose with the JavaScript spread operator `...`. This type can be used for tuple concatenation as well as for variadic functions.
900
-
901
- ```typescript
902
- // TypeScript
903
-
904
- type T = [number, number] // type T = [number, number]
905
-
906
- type C = [...T, number] // type C = [number, number, number]
907
-
908
- type F = (...param: C) => void // type F = (
909
- // param0: number,
910
- // param1: number,
911
- // param2: number
912
- // ) => void
913
-
914
- // TypeBox
915
-
916
- const T = Type.Tuple([ // const T: TTuple<[
917
- Type.Number(), // TNumber,
918
- Type.Number() // TNumber
919
- ]) // ]>
920
-
921
- const C = Type.Tuple([ // const C: TTuple<[
922
- ...Type.Rest(T), // TNumber,
923
- Type.Number() // TNumber,
924
- ]) // TNumber
925
- // ]>
926
-
927
- const F = Type.Function(Type.Rest(C), Type.Void()) // const F: TFunction<[
928
- // TNumber,
929
- // TNumber,
930
- // TNumber
931
- // ], TVoid>
932
- ```
933
- <a name='types-unsafe'></a>
934
-
935
- ### Unsafe Types
936
-
937
- Use `Type.Unsafe` to create custom schematics with user defined inference rules.
938
-
939
- ```typescript
940
- const T = Type.Unsafe<string>({ type: 'number' }) // const T = {
941
- // type: 'number'
942
- // }
943
-
944
- type T = Static<typeof T> // type T = string
945
- ```
946
-
947
- The `Type.Unsafe` type can be useful to express specific OpenAPI schema representations.
948
-
949
- ```typescript
950
- import { Type, Static, TSchema } from '@sinclair/typebox'
951
-
952
- // Nullable<T>
953
-
954
- function Nullable<T extends TSchema>(schema: T) {
955
- return Type.Unsafe<Static<T> | null>({ ...schema, nullable: true })
956
- }
957
-
958
- const T = Nullable(Type.String()) // const T = {
959
- // type: 'string',
960
- // nullable: true
961
- // }
962
-
963
- type T = Static<typeof T> // type T = string | null
964
-
965
- // StringEnum<string[]>
966
-
967
- function StringEnum<T extends string[]>(values: [...T]) {
968
- return Type.Unsafe<T[number]>({ type: 'string', enum: values })
969
- }
970
-
971
- const T = StringEnum(['A', 'B', 'C']) // const T = {
972
- // enum: ['A', 'B', 'C']
973
- // }
974
-
975
- type T = Static<typeof T> // type T = 'A' | 'B' | 'C'
976
- ```
977
-
978
- <a name='types-guards'></a>
979
-
980
- ### Type Guards
981
-
982
- TypeBox provides a `TypeGuard` module that can be used for reflection and asserting values as types.
983
-
984
- ```typescript
985
- import { Type, TypeGuard } from '@sinclair/typebox'
986
-
987
- const T = Type.String()
988
-
989
- if(TypeGuard.TString(T)) {
990
-
991
- // T is TString
992
- }
993
- ```
994
-
995
- <a name='types-strict'></a>
996
-
997
- ### Strict
998
-
999
- TypeBox schemas contain the `Kind` and `Modifier` symbol properties. These properties are used for type composition and 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.
1000
-
1001
- ```typescript
1002
- const T = Type.Object({ // const T = {
1003
- name: Type.Optional(Type.String()) // [Kind]: 'Object',
1004
- }) // type: 'object',
1005
- // properties: {
1006
- // name: {
1007
- // [Kind]: 'String',
1008
- // type: 'string',
1009
- // [Modifier]: 'Optional'
1010
- // }
1011
- // }
1012
- // }
1013
-
1014
- const U = Type.Strict(T) // const U = {
1015
- // type: 'object',
1016
- // properties: {
1017
- // name: {
1018
- // type: 'string'
1019
- // }
1020
- // }
1021
- // }
1022
- ```
1023
-
1024
- <a name='values'></a>
1025
-
1026
- ## Values
1027
-
1028
- 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 optional import.
1029
-
1030
- ```typescript
1031
- import { Value } from '@sinclair/typebox/value'
1032
- ```
1033
-
1034
- <a name='values-create'></a>
1035
-
1036
- ### Create
1037
-
1038
- Use the Create function to create a value from a type. TypeBox will use default values if specified.
1039
-
1040
- ```typescript
1041
- const T = Type.Object({ x: Type.Number(), y: Type.Number({ default: 42 }) })
1042
-
1043
- const A = Value.Create(T) // const A = { x: 0, y: 42 }
1044
- ```
1045
-
1046
- <a name='values-clone'></a>
1047
-
1048
- ### Clone
1049
-
1050
- Use the Clone function to deeply clone a value
1051
-
1052
- ```typescript
1053
- const A = Value.Clone({ x: 1, y: 2, z: 3 }) // const A = { x: 1, y: 2, z: 3 }
1054
- ```
1055
-
1056
- <a name='values-check'></a>
1057
-
1058
- ### Check
1059
-
1060
- Use the Check function to type check a value
1061
-
1062
- ```typescript
1063
- const T = Type.Object({ x: Type.Number() })
1064
-
1065
- const R = Value.Check(T, { x: 1 }) // const R = true
1066
- ```
1067
-
1068
- <a name='values-convert'></a>
1069
-
1070
- ### Convert
1071
-
1072
- Use the Convert function to convert a value into its target type if a reasonable conversion is possible.
1073
-
1074
- ```typescript
1075
- const T = Type.Object({ x: Type.Number() })
1076
-
1077
- const R1 = Value.Convert(T, { x: '3.14' }) // const R1 = { x: 3.14 }
1078
-
1079
- const R2 = Value.Convert(T, { x: 'not a number' }) // const R2 = { x: 'not a number' }
1080
- ```
1081
-
1082
- <a name='values-cast'></a>
1083
-
1084
- ### Cast
1085
-
1086
- 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.
1087
-
1088
- ```typescript
1089
- const T = Type.Object({ x: Type.Number(), y: Type.Number() }, { additionalProperties: false })
1090
-
1091
- const X = Value.Cast(T, null) // const X = { x: 0, y: 0 }
1092
-
1093
- const Y = Value.Cast(T, { x: 1 }) // const Y = { x: 1, y: 0 }
1094
-
1095
- const Z = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const Z = { x: 1, y: 2 }
1096
- ```
1097
-
1098
- <a name='values-equal'></a>
1099
-
1100
- ### Equal
1101
-
1102
- Use the Equal function to deeply check for value equality.
1103
-
1104
- ```typescript
1105
- const R = Value.Equal( // const R = true
1106
- { x: 1, y: 2, z: 3 },
1107
- { x: 1, y: 2, z: 3 }
1108
- )
1109
- ```
1110
-
1111
- <a name='values-hash'></a>
1112
-
1113
- ### Hash
1114
-
1115
- Use the Hash function to create a [FNV1A-64](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function) non cryptographic hash of a value.
1116
-
1117
- ```typescript
1118
- const A = Value.Hash({ x: 1, y: 2, z: 3 }) // const A = 2910466848807138541n
1119
-
1120
- const B = Value.Hash({ x: 1, y: 4, z: 3 }) // const B = 1418369778807423581n
1121
- ```
1122
-
1123
- <a name='values-diff'></a>
1124
-
1125
- ### Diff
1126
-
1127
- Use the Diff function to produce a sequence of edits to transform one value into another.
1128
-
1129
- ```typescript
1130
- const E = Value.Diff( // const E = [
1131
- { x: 1, y: 2, z: 3 }, // { type: 'update', path: '/y', value: 4 },
1132
- { y: 4, z: 5, w: 6 } // { type: 'update', path: '/z', value: 5 },
1133
- ) // { type: 'insert', path: '/w', value: 6 },
1134
- // { type: 'delete', path: '/x' }
1135
- // ]
1136
- ```
1137
-
1138
- <a name='values-patch'></a>
1139
-
1140
- ### Patch
1141
-
1142
- Use the Patch function to apply edits
1143
-
1144
- ```typescript
1145
- const A = { x: 1, y: 2 }
1146
-
1147
- const B = { x: 3 }
1148
-
1149
- const E = Value.Diff(A, B) // const E = [
1150
- // { type: 'update', path: '/x', value: 3 },
1151
- // { type: 'delete', path: '/y' }
1152
- // ]
1153
-
1154
- const C = Value.Patch<typeof B>(A, E) // const C = { x: 3 }
1155
- ```
1156
-
1157
- <a name='values-errors'></a>
1158
-
1159
- ### Errors
1160
-
1161
- Use the Errors function enumerate validation errors.
1162
-
1163
- ```typescript
1164
- const T = Type.Object({ x: Type.Number(), y: Type.Number() })
1165
-
1166
- const R = [...Value.Errors(T, { x: '42' })] // const R = [{
1167
- // schema: { type: 'number' },
1168
- // path: '/x',
1169
- // value: '42',
1170
- // message: 'Expected number'
1171
- // }, {
1172
- // schema: { type: 'number' },
1173
- // path: '/y',
1174
- // value: undefined,
1175
- // message: 'Expected number'
1176
- // }]
1177
- ```
1178
-
1179
- <a name='values-mutate'></a>
1180
-
1181
- ### Mutate
1182
-
1183
- Use the Mutate function to perform a deep mutable value assignment while retaining internal references.
1184
-
1185
- ```typescript
1186
- const Y = { z: 1 } // const Y = { z: 1 }
1187
-
1188
- const X = { y: Y } // const X = { y: { z: 1 } }
1189
-
1190
- const A = { x: X } // const A = { x: { y: { z: 1 } } }
1191
-
1192
-
1193
- Value.Mutate(A, { x: { y: { z: 2 } } }) // const A' = { x: { y: { z: 2 } } }
1194
-
1195
- const R0 = A.x.y.z === 2 // const R0 = true
1196
-
1197
- const R1 = A.x.y === Y // const R1 = true
1198
-
1199
- const R2 = A.x === X // const R2 = true
1200
- ```
1201
-
1202
- <a name='values-pointer'></a>
1203
-
1204
- ### Pointer
1205
-
1206
- Use ValuePointer to perform mutable updates on existing values using [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) JSON Pointers.
1207
-
1208
- ```typescript
1209
- import { ValuePointer } from '@sinclair/typebox/value'
1210
-
1211
- const A = { x: 0, y: 0, z: 0 }
1212
-
1213
- ValuePointer.Set(A, '/x', 1) // const A' = { x: 1, y: 0, z: 0 }
1214
-
1215
- ValuePointer.Set(A, '/y', 1) // const A' = { x: 1, y: 1, z: 0 }
1216
-
1217
- ValuePointer.Set(A, '/z', 1) // const A' = { x: 1, y: 1, z: 1 }
1218
- ```
1219
-
1220
- <a name='typecheck'></a>
1221
-
1222
- ## TypeCheck
1223
-
1224
- 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.
1225
-
1226
- The following sections detail using Ajv and TypeBox's compiler infrastructure.
1227
-
1228
- <a name='typecheck-ajv'></a>
1229
-
1230
- ## Ajv
1231
-
1232
- The following shows the recommended setup for Ajv.
1233
-
1234
- ```bash
1235
- $ npm install ajv ajv-formats --save
1236
- ```
1237
-
1238
- ```typescript
1239
- import { Type } from '@sinclair/typebox'
1240
- import addFormats from 'ajv-formats'
1241
- import Ajv from 'ajv'
1242
-
1243
- const ajv = addFormats(new Ajv({}), [
1244
- 'date-time',
1245
- 'time',
1246
- 'date',
1247
- 'email',
1248
- 'hostname',
1249
- 'ipv4',
1250
- 'ipv6',
1251
- 'uri',
1252
- 'uri-reference',
1253
- 'uuid',
1254
- 'uri-template',
1255
- 'json-pointer',
1256
- 'relative-json-pointer',
1257
- 'regex'
1258
- ])
1259
-
1260
- const C = ajv.compile(Type.Object({
1261
- x: Type.Number(),
1262
- y: Type.Number(),
1263
- z: Type.Number()
1264
- }))
1265
-
1266
- const R = C({ x: 1, y: 2, z: 3 }) // const R = true
1267
- ```
1268
-
1269
- <a name='typecheck-typecompiler'></a>
1270
-
1271
- ### TypeCompiler
1272
-
1273
- 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.
1274
-
1275
- The TypeCompiler is provided as an optional import.
1276
-
1277
- ```typescript
1278
- import { TypeCompiler } from '@sinclair/typebox/compiler'
1279
- ```
1280
-
1281
- Use the `Compile(...)` function to compile a type. Note that compilation is an expensive operation that should typically be performed once per type during application start up. TypeBox does not cache previously compiled types, so applications are expected to hold references to each compiled type for the lifetime of the application.
1282
-
1283
- ```typescript
1284
- const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{
1285
- x: Type.Number(), // x: TNumber;
1286
- y: Type.Number(), // y: TNumber;
1287
- z: Type.Number() // z: TNumber;
1288
- })) // }>>
1289
-
1290
- const R = C.Check({ x: 1, y: 2, z: 3 }) // const R = true
1291
- ```
1292
-
1293
- 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.
1294
-
1295
- ```typescript
1296
- const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{
1297
- x: Type.Number(), // x: TNumber;
1298
- y: Type.Number(), // y: TNumber;
1299
- z: Type.Number() // z: TNumber;
1300
- })) // }>>
1301
-
1302
- const value = { }
1303
-
1304
- const errors = [...C.Errors(value)] // const errors = [{
1305
- // schema: { type: 'number' },
1306
- // path: '/x',
1307
- // value: undefined,
1308
- // message: 'Expected number'
1309
- // }, {
1310
- // schema: { type: 'number' },
1311
- // path: '/y',
1312
- // value: undefined,
1313
- // message: 'Expected number'
1314
- // }, {
1315
- // schema: { type: 'number' },
1316
- // path: '/z',
1317
- // value: undefined,
1318
- // message: 'Expected number'
1319
- // }]
1320
- ```
1321
-
1322
- Compiled routines can be inspected with the `.Code()` function.
1323
-
1324
- ```typescript
1325
- const C = TypeCompiler.Compile(Type.String()) // const C: TypeCheck<TString>
1326
-
1327
- console.log(C.Code()) // return function check(value) {
1328
- // return (
1329
- // (typeof value === 'string')
1330
- // )
1331
- // }
1332
- ```
1333
-
1334
- <a name='typesystem'></a>
1335
-
1336
- ## TypeSystem
1337
-
1338
- The TypeBox TypeSystem module provides functionality to define types above and beyond the Standard and Extended type sets as well as control various assertion policies. Configurations made to the TypeSystem module are observed by both `TypeCompiler` and `Value` modules.
1339
-
1340
- The TypeSystem module is provided as an optional import.
1341
-
1342
- ```typescript
1343
- import { TypeSystem } from '@sinclair/typebox/system'
1344
- ```
1345
-
1346
- <a name='typesystem-types'></a>
1347
-
1348
- ### Types
1349
-
1350
- Use the `Type(...)` function to create custom types. This function lets you specify custom value assertion logic and will return a type factory function which is used to instance the type. This function accepts two generic arguments, the first is the inference type, the second is options used to constrain the type. The following creates a Vector type.
1351
-
1352
- ```typescript
1353
- type VectorOptions = { abs: boolean }
1354
-
1355
- type Vector = { x: number, y: number }
1356
-
1357
- const Vector = TypeSystem.Type<Vector, VectorOptions>('Vector', (options, value) => {
1358
- return (
1359
- typeof value === 'object' && value !== null &&
1360
- 'x' in value && typeof value.x === 'number' &&
1361
- 'y' in value && typeof value.y === 'number' &&
1362
- (options.abs ? (value.x === Math.abs(value.x) && value.y === Math.abs(value.y)) : true)
1363
- )
1364
- })
1365
-
1366
- const T = Vector({ abs: true })
1367
-
1368
- type T = Static<typeof T> // type T = Vector
1369
-
1370
- const R1 = Value.Check(T, { x: 1, y: 1 }) // const R1 = true
1371
-
1372
- const R2 = Value.Check(T, { x: 1, y: '1' }) // const R2 = false
1373
-
1374
- const R3 = Value.Check(T, { x: 1, y: -1 }) // const R3 = false
1375
- ```
1376
-
1377
- <a name='typesystem-formats'></a>
1378
-
1379
- ### Formats
1380
-
1381
- Use the `Format(...)` function to create a custom string format. The following creates a format that checks for lowercase strings.
1382
-
1383
- ```typescript
1384
- TypeSystem.Format('lowercase', value => value === value.toLowerCase()) // format should be lowercase
1385
-
1386
- const T = Type.String({ format: 'lowercase' })
1387
-
1388
- const A = Value.Check(T, 'Hello') // const A = false
1389
-
1390
- const B = Value.Check(T, 'hello') // const B = true
1391
- ```
1392
-
1393
- <a name='typesystem-policies'></a>
1394
-
1395
- ### Policies
1396
-
1397
- TypeBox validates using standard JSON Schema assertion policies by default. It is possible to override some of these policies to have TypeBox assert inline with TypeScript static assertion rules. The following policy overrides are available.
1398
-
1399
- ```typescript
1400
- // Disallow undefined values for optional properties (default is false)
1401
- //
1402
- // const A: { x?: number } = { x: undefined } - disallowed when enabled
1403
-
1404
- TypeSystem.ExactOptionalPropertyTypes = true
1405
-
1406
- // Allow arrays to validate as object types (default is false)
1407
- //
1408
- // const A: {} = [] - allowed in TS
1409
-
1410
- TypeSystem.AllowArrayObjects = true
1411
-
1412
- // Allow numeric values to be NaN or + or - Infinity (default is false)
1413
- //
1414
- // const A: number = NaN - allowed in TS
1415
-
1416
- TypeSystem.AllowNaN = true
1417
- ```
1418
-
1419
- <a name='workbench'></a>
1420
-
1421
- ## Workbench
1422
-
1423
- TypeBox offers a small web based code generation tool that can be used to convert TypeScript types into TypeBox type definitions as well as a variety of other formats.
1424
-
1425
- [Workbench Link Here](https://sinclairzx81.github.io/typebox-workbench/)
1426
-
1427
- <div align='center'>
1428
-
1429
- <a href="https://sinclairzx81.github.io/typebox-workbench/"><img src="https://github.com/sinclairzx81/typebox/blob/master/workbench.png?raw=true" /></a>
1430
-
1431
- </div>
1432
-
1433
- <a name='ecosystem'></a>
1434
-
1435
- ## Ecosystem
1436
-
1437
- The following is a list of community packages that provide general tooling and framework support for TypeBox.
1438
-
1439
- | Package | Description |
1440
- | ------------- | ------------- |
1441
- | [elysia](https://github.com/elysiajs/elysia) | Fast and friendly Bun web framework |
1442
- | [fastify-type-provider-typebox](https://github.com/fastify/fastify-type-provider-typebox) | Fastify TypeBox integration with the Fastify Type Provider |
1443
- | [fetch-typebox](https://github.com/erfanium/fetch-typebox) | Drop-in replacement for fetch that brings easy integration with TypeBox |
1444
- | [schema2typebox](https://github.com/xddq/schema2typebox) | Creating TypeBox code from JSON schemas |
1445
- | [ts2typebox](https://github.com/xddq/ts2typebox) | Creating TypeBox code from Typescript types |
1446
-
1447
- <a name='benchmark'></a>
1448
-
1449
- ## Benchmark
1450
-
1451
- 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.0.0.
1452
-
1453
- For additional comparative benchmarks, please refer to [typescript-runtime-type-benchmarks](https://moltar.github.io/typescript-runtime-type-benchmarks/).
1454
-
1455
- <a name='benchmark-compile'></a>
1456
-
1457
- ### Compile
1458
-
1459
- This benchmark measures compilation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/compile.ts).
1460
-
1461
- ```typescript
1462
- ┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┐
1463
- │ (index) │ Iterations │ Ajv │ TypeCompiler │ Performance │
1464
- ├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┤
1465
- │ Literal_String │ 1000 │ ' 220 ms' │ ' 6 ms' │ ' 36.67 x' │
1466
- │ Literal_Number │ 1000 │ ' 172 ms' │ ' 4 ms' │ ' 43.00 x' │
1467
- │ Literal_Boolean │ 1000 │ ' 162 ms' │ ' 4 ms' │ ' 40.50 x' │
1468
- │ Primitive_Number │ 1000 │ ' 161 ms' │ ' 6 ms' │ ' 26.83 x' │
1469
- │ Primitive_String │ 1000 │ ' 154 ms' │ ' 4 ms' │ ' 38.50 x' │
1470
- │ Primitive_String_Pattern │ 1000 │ ' 204 ms' │ ' 10 ms' │ ' 20.40 x' │
1471
- │ Primitive_Boolean │ 1000 │ ' 131 ms' │ ' 4 ms' │ ' 32.75 x' │
1472
- │ Primitive_Null │ 1000 │ ' 142 ms' │ ' 5 ms' │ ' 28.40 x' │
1473
- │ Object_Unconstrained │ 1000 │ ' 1263 ms' │ ' 29 ms' │ ' 43.55 x' │
1474
- │ Object_Constrained │ 1000 │ ' 1267 ms' │ ' 24 ms' │ ' 52.79 x' │
1475
- │ Object_Vector3 │ 1000 │ ' 382 ms' │ ' 7 ms' │ ' 54.57 x' │
1476
- │ Object_Box3D │ 1000 │ ' 1723 ms' │ ' 28 ms' │ ' 61.54 x' │
1477
- │ Tuple_Primitive │ 1000 │ ' 495 ms' │ ' 13 ms' │ ' 38.08 x' │
1478
- │ Tuple_Object │ 1000 │ ' 1271 ms' │ ' 16 ms' │ ' 79.44 x' │
1479
- │ Composite_Intersect │ 1000 │ ' 656 ms' │ ' 19 ms' │ ' 34.53 x' │
1480
- │ Composite_Union │ 1000 │ ' 529 ms' │ ' 18 ms' │ ' 29.39 x' │
1481
- │ Math_Vector4 │ 1000 │ ' 802 ms' │ ' 14 ms' │ ' 57.29 x' │
1482
- │ Math_Matrix4 │ 1000 │ ' 411 ms' │ ' 6 ms' │ ' 68.50 x' │
1483
- │ Array_Primitive_Number │ 1000 │ ' 369 ms' │ ' 6 ms' │ ' 61.50 x' │
1484
- │ Array_Primitive_String │ 1000 │ ' 369 ms' │ ' 4 ms' │ ' 92.25 x' │
1485
- │ Array_Primitive_Boolean │ 1000 │ ' 297 ms' │ ' 3 ms' │ ' 99.00 x' │
1486
- │ Array_Object_Unconstrained │ 1000 │ ' 1582 ms' │ ' 20 ms' │ ' 79.10 x' │
1487
- │ Array_Object_Constrained │ 1000 │ ' 1629 ms' │ ' 19 ms' │ ' 85.74 x' │
1488
- │ Array_Tuple_Primitive │ 1000 │ ' 652 ms' │ ' 12 ms' │ ' 54.33 x' │
1489
- │ Array_Tuple_Object │ 1000 │ ' 1587 ms' │ ' 16 ms' │ ' 99.19 x' │
1490
- │ Array_Composite_Intersect │ 1000 │ ' 1051 ms' │ ' 15 ms' │ ' 70.07 x' │
1491
- │ Array_Composite_Union │ 1000 │ ' 733 ms' │ ' 15 ms' │ ' 48.87 x' │
1492
- │ Array_Math_Vector4 │ 1000 │ ' 1071 ms' │ ' 12 ms' │ ' 89.25 x' │
1493
- │ Array_Math_Matrix4 │ 1000 │ ' 636 ms' │ ' 5 ms' │ ' 127.20 x' │
1494
- └────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┘
1495
- ```
1496
-
1497
- <a name='benchmark-validate'></a>
1498
-
1499
- ### Validate
1500
-
1501
- This benchmark measures validation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/check.ts).
1502
-
1503
- ```typescript
1504
- ┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐
1505
- │ (index) │ Iterations │ ValueCheck │ Ajv │ TypeCompiler │ Performance │
1506
- ├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
1507
- │ Literal_String │ 1000000 │ ' 24 ms' │ ' 5 ms' │ ' 5 ms' │ ' 1.00 x' │
1508
- │ Literal_Number │ 1000000 │ ' 21 ms' │ ' 17 ms' │ ' 9 ms' │ ' 1.89 x' │
1509
- │ Literal_Boolean │ 1000000 │ ' 18 ms' │ ' 18 ms' │ ' 9 ms' │ ' 2.00 x' │
1510
- │ Primitive_Number │ 1000000 │ ' 25 ms' │ ' 18 ms' │ ' 9 ms' │ ' 2.00 x' │
1511
- │ Primitive_String │ 1000000 │ ' 25 ms' │ ' 17 ms' │ ' 9 ms' │ ' 1.89 x' │
1512
- │ Primitive_String_Pattern │ 1000000 │ ' 174 ms' │ ' 44 ms' │ ' 36 ms' │ ' 1.22 x' │
1513
- │ Primitive_Boolean │ 1000000 │ ' 22 ms' │ ' 17 ms' │ ' 9 ms' │ ' 1.89 x' │
1514
- │ Primitive_Null │ 1000000 │ ' 22 ms' │ ' 16 ms' │ ' 9 ms' │ ' 1.78 x' │
1515
- │ Object_Unconstrained │ 1000000 │ ' 1065 ms' │ ' 33 ms' │ ' 25 ms' │ ' 1.32 x' │
1516
- │ Object_Constrained │ 1000000 │ ' 1192 ms' │ ' 53 ms' │ ' 38 ms' │ ' 1.39 x' │
1517
- │ Object_Vector3 │ 1000000 │ ' 410 ms' │ ' 23 ms' │ ' 14 ms' │ ' 1.64 x' │
1518
- │ Object_Box3D │ 1000000 │ ' 1939 ms' │ ' 54 ms' │ ' 50 ms' │ ' 1.08 x' │
1519
- │ Object_Recursive │ 1000000 │ ' 5248 ms' │ ' 355 ms' │ ' 149 ms' │ ' 2.38 x' │
1520
- │ Tuple_Primitive │ 1000000 │ ' 163 ms' │ ' 21 ms' │ ' 13 ms' │ ' 1.62 x' │
1521
- │ Tuple_Object │ 1000000 │ ' 737 ms' │ ' 29 ms' │ ' 20 ms' │ ' 1.45 x' │
1522
- │ Composite_Intersect │ 1000000 │ ' 761 ms' │ ' 24 ms' │ ' 15 ms' │ ' 1.60 x' │
1523
- │ Composite_Union │ 1000000 │ ' 519 ms' │ ' 23 ms' │ ' 13 ms' │ ' 1.77 x' │
1524
- │ Math_Vector4 │ 1000000 │ ' 247 ms' │ ' 21 ms' │ ' 11 ms' │ ' 1.91 x' │
1525
- │ Math_Matrix4 │ 1000000 │ ' 1045 ms' │ ' 39 ms' │ ' 27 ms' │ ' 1.44 x' │
1526
- │ Array_Primitive_Number │ 1000000 │ ' 256 ms' │ ' 20 ms' │ ' 12 ms' │ ' 1.67 x' │
1527
- │ Array_Primitive_String │ 1000000 │ ' 222 ms' │ ' 21 ms' │ ' 14 ms' │ ' 1.50 x' │
1528
- │ Array_Primitive_Boolean │ 1000000 │ ' 149 ms' │ ' 22 ms' │ ' 16 ms' │ ' 1.38 x' │
1529
- │ Array_Object_Unconstrained │ 1000000 │ ' 5473 ms' │ ' 67 ms' │ ' 59 ms' │ ' 1.14 x' │
1530
- │ Array_Object_Constrained │ 1000000 │ ' 5548 ms' │ ' 130 ms' │ ' 116 ms' │ ' 1.12 x' │
1531
- │ Array_Object_Recursive │ 1000000 │ ' 21047 ms' │ ' 1710 ms' │ ' 584 ms' │ ' 2.93 x' │
1532
- │ Array_Tuple_Primitive │ 1000000 │ ' 691 ms' │ ' 35 ms' │ ' 29 ms' │ ' 1.21 x' │
1533
- │ Array_Tuple_Object │ 1000000 │ ' 3075 ms' │ ' 63 ms' │ ' 50 ms' │ ' 1.26 x' │
1534
- │ Array_Composite_Intersect │ 1000000 │ ' 3126 ms' │ ' 44 ms' │ ' 35 ms' │ ' 1.26 x' │
1535
- │ Array_Composite_Union │ 1000000 │ ' 2086 ms' │ ' 68 ms' │ ' 33 ms' │ ' 2.06 x' │
1536
- │ Array_Math_Vector4 │ 1000000 │ ' 1069 ms' │ ' 38 ms' │ ' 23 ms' │ ' 1.65 x' │
1537
- │ Array_Math_Matrix4 │ 1000000 │ ' 4559 ms' │ ' 111 ms' │ ' 88 ms' │ ' 1.26 x' │
1538
- └────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘
1539
- ```
1540
-
1541
- <a name='benchmark-compression'></a>
1542
-
1543
- ### Compression
1544
-
1545
- The following table lists esbuild compiled and minified sizes for each TypeBox module.
1546
-
1547
- ```typescript
1548
- ┌──────────────────────┬────────────┬────────────┬─────────────┐
1549
- │ (index) │ Compiled │ Minified │ Compression │
1550
- ├──────────────────────┼────────────┼────────────┼─────────────┤
1551
- │ typebox/compiler │ '128.0 kb' │ ' 57.0 kb' │ '2.25 x' │
1552
- │ typebox/errors │ '111.6 kb' │ ' 49.1 kb' │ '2.27 x' │
1553
- │ typebox/system │ ' 77.0 kb' │ ' 31.5 kb' │ '2.45 x' │
1554
- │ typebox/value │ '177.7 kb' │ ' 76.8 kb' │ '2.31 x' │
1555
- │ typebox │ ' 75.9 kb' │ ' 31.0 kb' │ '2.45 x' │
1556
- └──────────────────────┴────────────┴────────────┴─────────────┘
1557
- ```
1558
-
1559
- <a name='contribute'></a>
1560
-
1561
- ## Contribute
1562
-
1563
- 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.
1
+ <div align='center'>
2
+
3
+ <h1>TypeBox</h1>
4
+
5
+ <p>JSON Schema Type Builder with Static Type Resolution for TypeScript</p>
6
+
7
+ <img src="https://github.com/sinclairzx81/typebox/blob/master/typebox.png?raw=true" />
8
+
9
+ <br />
10
+ <br />
11
+
12
+ [![npm version](https://badge.fury.io/js/%40sinclair%2Ftypebox.svg)](https://badge.fury.io/js/%40sinclair%2Ftypebox)
13
+ [![Downloads](https://img.shields.io/npm/dm/%40sinclair%2Ftypebox.svg)](https://www.npmjs.com/package/%40sinclair%2Ftypebox)
14
+ [![GitHub CI](https://github.com/sinclairzx81/typebox/workflows/GitHub%20CI/badge.svg)](https://github.com/sinclairzx81/typebox/actions)
15
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
16
+
17
+ </div>
18
+
19
+ <a name="Install"></a>
20
+
21
+ ## Install
22
+
23
+ #### Npm
24
+ ```bash
25
+ $ npm install @sinclair/typebox --save
26
+ ```
27
+
28
+ #### Deno
29
+ ```typescript
30
+ import { Static, Type } from 'npm:@sinclair/typebox'
31
+ ```
32
+
33
+ #### Esm
34
+
35
+ ```typescript
36
+ import { Static, Type } from 'https://esm.sh/@sinclair/typebox'
37
+ ```
38
+
39
+ ## Example
40
+
41
+ ```typescript
42
+ import { Static, Type } from '@sinclair/typebox'
43
+
44
+ const T = Type.Object({ // const T = {
45
+ x: Type.Number(), // type: 'object',
46
+ y: Type.Number(), // required: ['x', 'y', 'z'],
47
+ z: Type.Number() // properties: {
48
+ }) // x: { type: 'number' },
49
+ // y: { type: 'number' },
50
+ // z: { type: 'number' }
51
+ // }
52
+ // }
53
+
54
+ type T = Static<typeof T> // type T = {
55
+ // x: number,
56
+ // y: number,
57
+ // z: number
58
+ // }
59
+ ```
60
+
61
+
62
+ <a name="Overview"></a>
63
+
64
+ ## Overview
65
+
66
+ TypeBox is a runtime type builder that creates 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 assertion 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.
67
+
68
+ 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 or RPC services to help validate data received over the wire.
69
+
70
+ License MIT
71
+
72
+ ## Contents
73
+ - [Install](#install)
74
+ - [Overview](#overview)
75
+ - [Usage](#usage)
76
+ - [Types](#types)
77
+ - [Standard](#types-standard)
78
+ - [Extended](#types-extended)
79
+ - [Modifiers](#types-modifiers)
80
+ - [Options](#types-options)
81
+ - [Generics](#types-generics)
82
+ - [References](#types-references)
83
+ - [Recursive](#types-recursive)
84
+ - [Conditional](#types-conditional)
85
+ - [Template Literal](#types-template-literal)
86
+ - [Indexed](#types-indexed)
87
+ - [Rest](#types-rest)
88
+ - [Guards](#types-guards)
89
+ - [Unsafe](#types-unsafe)
90
+ - [Strict](#types-strict)
91
+ - [Values](#values)
92
+ - [Create](#values-create)
93
+ - [Clone](#values-clone)
94
+ - [Check](#values-check)
95
+ - [Convert](#values-convert)
96
+ - [Cast](#values-cast)
97
+ - [Equal](#values-equal)
98
+ - [Hash](#values-hash)
99
+ - [Diff](#values-diff)
100
+ - [Patch](#values-patch)
101
+ - [Errors](#values-errors)
102
+ - [Mutate](#values-mutate)
103
+ - [Pointer](#values-pointer)
104
+ - [TypeCheck](#typecheck)
105
+ - [Ajv](#typecheck-ajv)
106
+ - [TypeCompiler](#typecheck-typecompiler)
107
+ - [TypeSystem](#typesystem)
108
+ - [Types](#typesystem-types)
109
+ - [Formats](#typesystem-formats)
110
+ - [Policies](#typesystem-policies)
111
+ - [Workbench](#workbench)
112
+ - [Ecosystem](#ecosystem)
113
+ - [Benchmark](#benchmark)
114
+ - [Compile](#benchmark-compile)
115
+ - [Validate](#benchmark-validate)
116
+ - [Compression](#benchmark-compression)
117
+ - [Contribute](#contribute)
118
+
119
+ <a name="usage"></a>
120
+
121
+ ## Usage
122
+
123
+ The following shows general usage.
124
+
125
+ ```typescript
126
+ import { Static, Type } from '@sinclair/typebox'
127
+
128
+ //--------------------------------------------------------------------------------------------
129
+ //
130
+ // Let's say you have the following type ...
131
+ //
132
+ //--------------------------------------------------------------------------------------------
133
+
134
+ type T = {
135
+ id: string,
136
+ name: string,
137
+ timestamp: number
138
+ }
139
+
140
+ //--------------------------------------------------------------------------------------------
141
+ //
142
+ // ... you can express this type in the following way.
143
+ //
144
+ //--------------------------------------------------------------------------------------------
145
+
146
+ const T = Type.Object({ // const T = {
147
+ id: Type.String(), // type: 'object',
148
+ name: Type.String(), // properties: {
149
+ timestamp: Type.Integer() // id: {
150
+ }) // type: 'string'
151
+ // },
152
+ // name: {
153
+ // type: 'string'
154
+ // },
155
+ // timestamp: {
156
+ // type: 'integer'
157
+ // }
158
+ // },
159
+ // required: [
160
+ // 'id',
161
+ // 'name',
162
+ // 'timestamp'
163
+ // ]
164
+ // }
165
+
166
+ //--------------------------------------------------------------------------------------------
167
+ //
168
+ // ... then infer back to the original static type this way.
169
+ //
170
+ //--------------------------------------------------------------------------------------------
171
+
172
+ type T = Static<typeof T> // type T = {
173
+ // id: string,
174
+ // name: string,
175
+ // timestamp: number
176
+ // }
177
+
178
+ //--------------------------------------------------------------------------------------------
179
+ //
180
+ // ... then use the type both as JSON schema and as a TypeScript type.
181
+ //
182
+ //--------------------------------------------------------------------------------------------
183
+
184
+ import { Value } from '@sinclair/typebox/value'
185
+
186
+ function receive(value: T) { // ... as a Static Type
187
+
188
+ if(Value.Check(T, value)) { // ... as a JSON Schema
189
+
190
+ // ok...
191
+ }
192
+ }
193
+ ```
194
+
195
+ <a name='types'></a>
196
+
197
+ ## Types
198
+
199
+ TypeBox types are JSON schema fragments that can be composed into more complex types. Each fragment is structured such that a JSON schema compliant validator can runtime assert a value the same way TypeScript will statically assert a type. TypeBox provides a set of Standard types which are used create JSON schema compliant schematics as well as an Extended type set used to create schematics for constructs native to JavaScript.
200
+
201
+ <a name='types-standard'></a>
202
+
203
+ ### Standard Types
204
+
205
+ The following table lists the Standard TypeBox types. These types are fully compatible with the JSON Schema Draft 6 specification.
206
+
207
+ ```typescript
208
+ ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
209
+ │ TypeBox │ TypeScript │ JSON Schema │
210
+ │ │ │ │
211
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
212
+ │ const T = Type.Any() │ type T = any │ const T = { } │
213
+ │ │ │ │
214
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
215
+ │ const T = Type.Unknown() │ type T = unknown │ const T = { } │
216
+ │ │ │ │
217
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
218
+ │ const T = Type.String() │ type T = string │ const T = { │
219
+ │ │ │ type: 'string' │
220
+ │ │ │ } │
221
+ │ │ │ │
222
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
223
+ │ const T = Type.Number() │ type T = number │ const T = { │
224
+ │ │ │ type: 'number' │
225
+ │ │ │ } │
226
+ │ │ │ │
227
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
228
+ │ const T = Type.Integer() │ type T = number │ const T = { │
229
+ │ │ │ type: 'integer' │
230
+ │ │ │ } │
231
+ │ │ │ │
232
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
233
+ │ const T = Type.Boolean() │ type T = boolean │ const T = { │
234
+ │ │ │ type: 'boolean' │
235
+ │ │ │ } │
236
+ │ │ │ │
237
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
238
+ │ const T = Type.Null() │ type T = null │ const T = { │
239
+ │ │ │ type: 'null' │
240
+ │ │ │ } │
241
+ │ │ │ │
242
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
243
+ │ const T = Type.Literal(42) │ type T = 42 │ const T = { │
244
+ │ │ │ const: 42, │
245
+ │ │ │ type: 'number' │
246
+ │ │ │ } │
247
+ │ │ │ │
248
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
249
+ │ const T = Type.Array( │ type T = number[] │ const T = { │
250
+ │ Type.Number() │ │ type: 'array', │
251
+ │ ) │ │ items: { │
252
+ │ │ │ type: 'number' │
253
+ │ │ │ } │
254
+ │ │ │ } │
255
+ │ │ │ │
256
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
257
+ │ const T = Type.Object({ │ type T = { │ const T = { │
258
+ │ x: Type.Number(), │ x: number, │ type: 'object', │
259
+ │ y: Type.Number() │ y: number │ required: ['x', 'y'], │
260
+ │ }) │ } │ properties: { │
261
+ │ │ │ x: { │
262
+ │ │ │ type: 'number' │
263
+ │ │ │ }, │
264
+ │ │ │ y: { │
265
+ │ │ │ type: 'number' │
266
+ │ │ │ } │
267
+ │ │ │ } │
268
+ │ │ │ } │
269
+ │ │ │ │
270
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
271
+ │ const T = Type.Tuple([ │ type T = [number, number] │ const T = { │
272
+ │ Type.Number(), │ │ type: 'array', │
273
+ │ Type.Number() │ │ items: [{ │
274
+ │ ]) │ │ type: 'number' │
275
+ │ │ │ }, { │
276
+ │ │ │ type: 'number' │
277
+ │ │ │ }], │
278
+ │ │ │ additionalItems: false, │
279
+ │ │ │ minItems: 2, │
280
+ │ │ │ maxItems: 2 │
281
+ │ │ │ } │
282
+ │ │ │ │
283
+ │ │ │ │
284
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
285
+ │ enum Foo { │ enum Foo { │ const T = { │
286
+ │ A, │ A, │ anyOf: [{ │
287
+ │ B │ B │ type: 'number', │
288
+ │ } │ } │ const: 0 │
289
+ │ │ │ }, { │
290
+ │ const T = Type.Enum(Foo) │ type T = Foo │ type: 'number', │
291
+ │ │ │ const: 1 │
292
+ │ │ │ }] │
293
+ │ │ │ } │
294
+ │ │ │ │
295
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
296
+ │ const T = Type.KeyOf( │ type T = keyof { │ const T = { │
297
+ │ Type.Object({ │ x: number, │ anyOf: [{ │
298
+ │ x: Type.Number(), │ y: number │ type: 'string', │
299
+ │ y: Type.Number() │ } │ const: 'x' │
300
+ │ }) │ │ }, { │
301
+ │ ) │ │ type: 'string', │
302
+ │ │ │ const: 'y' │
303
+ │ │ │ }] │
304
+ │ │ │ } │
305
+ │ │ │ │
306
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
307
+ │ const T = Type.Union([ │ type T = string | number │ const T = { │
308
+ │ Type.String(), │ │ anyOf: [{ │
309
+ │ Type.Number() │ │ type: 'string' │
310
+ │ ]) │ │ }, { │
311
+ │ │ │ type: 'number' │
312
+ │ │ │ }] │
313
+ │ │ │ } │
314
+ │ │ │ │
315
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
316
+ │ const T = Type.Intersect([ │ type T = { │ const T = { │
317
+ │ Type.Object({ │ x: number │ allOf: [{ │
318
+ │ x: Type.Number() │ } & { │ type: 'object', │
319
+ │ }), │ y: number │ required: ['x'], │
320
+ │ Type.Object({ │ } │ properties: { │
321
+ │ y: Type.Number() │ │ x: { │
322
+ │ ]) │ │ type: 'number' │
323
+ │ ]) │ │ } │
324
+ │ │ │ } │
325
+ │ │ │ }, { │
326
+ │ │ │ type: 'object', |
327
+ │ │ │ required: ['y'], │
328
+ │ │ │ properties: { │
329
+ │ │ │ y: { │
330
+ │ │ │ type: 'number' │
331
+ │ │ │ } │
332
+ │ │ │ } │
333
+ │ │ │ }] │
334
+ │ │ │ } │
335
+ │ │ │ │
336
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
337
+ │ const T = Type.Composite([ │ type I = { │ const T = { │
338
+ │ Type.Object({ │ x: number │ type: 'object', │
339
+ │ x: Type.Number() │ } & { │ required: ['x', 'y'], │
340
+ │ }), │ y: number │ properties: { │
341
+ │ Type.Object({ │ } │ x: { │
342
+ │ y: Type.Number() │ │ type: 'number' │
343
+ │ }) │ type T = { │ }, │
344
+ │ ]) │ [K in keyof I]: I[K] │ y: { │
345
+ │ │ } │ type: 'number' │
346
+ │ │ │ } │
347
+ │ │ │ } │
348
+ │ │ │ } │
349
+ │ │ │ │
350
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
351
+ │ const T = Type.Never() │ type T = never │ const T = { │
352
+ │ │ │ not: {} │
353
+ │ │ │ } │
354
+ │ │ │ │
355
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
356
+ │ const T = Type.Not( | type T = string │ const T = { │
357
+ | Type.Union([ │ │ allOf: [{ │
358
+ │ Type.Literal('x'), │ │ not: { │
359
+ │ Type.Literal('y'), │ │ anyOf: [ │
360
+ │ Type.Literal('z') │ │ { const: 'x' }, │
361
+ │ ]), │ │ { const: 'y' }, │
362
+ │ Type.String() │ │ { const: 'z' } │
363
+ │ ) │ │ ] │
364
+ │ │ │ } │
365
+ │ │ │ }, { │
366
+ │ │ │ type: 'string' │
367
+ │ │ │ }] │
368
+ │ │ │ } │
369
+ │ │ │ │
370
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
371
+ │ const T = Type.Extends( │ type T = │ const T = { │
372
+ │ Type.String(), │ string extends number │ const: false, │
373
+ │ Type.Number(), │ true : false │ type: 'boolean' │
374
+ │ Type.Literal(true), │ │ } │
375
+ │ Type.Literal(false) │ │ │
376
+ │ ) │ │ │
377
+ │ │ │ │
378
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
379
+ │ const T = Type.Extract( │ type T = Extract< │ const T = { │
380
+ │ Type.Union([ │ string | number, │ type: 'string' │
381
+ │ Type.String(), │ string │ } │
382
+ │ Type.Number(), │ > │ │
383
+ │ ]), │ │ │
384
+ │ Type.String() │ │ │
385
+ │ ) │ │ │
386
+ │ │ │ │
387
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
388
+ │ const T = Type.Exclude( │ type T = Exclude< │ const T = { │
389
+ │ Type.Union([ │ string | number, │ type: 'number' │
390
+ │ Type.String(), │ string │ } │
391
+ │ Type.Number(), │ > │ │
392
+ │ ]), │ │ │
393
+ │ Type.String() │ │ │
394
+ │ ) │ │ │
395
+ │ │ │ │
396
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
397
+ │ const U = Type.Union([ │ type U = 'open' | 'close' │ const T = { │
398
+ │ Type.Literal('open'), │ │ type: 'string', │
399
+ │ Type.Literal('close') │ type T = `on${U}` │ pattern: '^on(open|close)$' │
400
+ │ ]) │ │ } │
401
+ │ │ │ │
402
+ │ const T = Type │ │ │
403
+ │ .TemplateLiteral([ │ │ │
404
+ │ Type.Literal('on'), │ │ │
405
+ │ U │ │ │
406
+ │ ]) │ │ │
407
+ │ │ │ │
408
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
409
+ │ const T = Type.Record( │ type T = Record< │ const T = { │
410
+ │ Type.String(), │ string, │ type: 'object', │
411
+ │ Type.Number() │ number │ patternProperties: { │
412
+ │ ) │ > │ '^.*$': { │
413
+ │ │ │ type: 'number' │
414
+ │ │ │ } │
415
+ │ │ │ } │
416
+ │ │ │ } │
417
+ │ │ │ │
418
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
419
+ │ const T = Type.Partial( │ type T = Partial<{ │ const T = { │
420
+ │ Type.Object({ │ x: number, │ type: 'object', │
421
+ │ x: Type.Number(), │ y: number │ properties: { │
422
+ │ y: Type.Number() | }> │ x: { │
423
+ │ }) │ │ type: 'number' │
424
+ │ ) │ │ }, │
425
+ │ │ │ y: { │
426
+ │ │ │ type: 'number' │
427
+ │ │ │ } │
428
+ │ │ │ } │
429
+ │ │ │ } │
430
+ │ │ │ │
431
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
432
+ │ const T = Type.Required( │ type T = Required<{ │ const T = { │
433
+ │ Type.Object({ │ x?: number, │ type: 'object', │
434
+ │ x: Type.Optional( │ y?: number │ required: ['x', 'y'], │
435
+ │ Type.Number() | }> │ properties: { │
436
+ │ ), │ │ x: { │
437
+ │ y: Type.Optional( │ │ type: 'number' │
438
+ │ Type.Number() │ │ }, │
439
+ │ ) │ │ y: { │
440
+ │ }) │ │ type: 'number' │
441
+ │ ) │ │ } │
442
+ │ │ │ } │
443
+ │ │ │ } │
444
+ │ │ │ │
445
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
446
+ │ const T = Type.Pick( │ type T = Pick<{ │ const T = { │
447
+ │ Type.Object({ │ x: number, │ type: 'object', │
448
+ │ x: Type.Number(), │ y: number │ required: ['x'], │
449
+ │ y: Type.Number() │ }, 'x'> │ properties: { │
450
+ │ }), ['x'] | │ x: { │
451
+ │ ) │ │ type: 'number' │
452
+ │ │ │ } │
453
+ │ │ │ } │
454
+ │ │ │ } │
455
+ │ │ │ │
456
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
457
+ │ const T = Type.Omit( │ type T = Omit<{ │ const T = { │
458
+ │ Type.Object({ │ x: number, │ type: 'object', │
459
+ │ x: Type.Number(), │ y: number │ required: ['y'], │
460
+ │ y: Type.Number() │ }, 'x'> │ properties: { │
461
+ │ }), ['x'] | │ y: { │
462
+ │ ) │ │ type: 'number' │
463
+ │ │ │ } │
464
+ │ │ │ } │
465
+ │ │ │ } │
466
+ │ │ │ │
467
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
468
+ │ const T = Type.Index( │ type T = { │ const T = { │
469
+ │ Type.Object({ │ x: number, │ type: 'number' │
470
+ │ x: Type.Number(), │ y: string │ } │
471
+ │ y: Type.String() │ }['x'] │ │
472
+ │ }), ['x'] │ │ │
473
+ │ ) │ │ │
474
+ │ │ │ │
475
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
476
+ │ const A = Type.Tuple([ │ type A = [0, 1] │ const T = { │
477
+ │ Type.Literal(0), │ type B = [2, 3] │ type: 'array', │
478
+ │ Type.Literal(1) │ type T = [...A, ...B] │ items: [ │
479
+ │ ]) │ │ { const: 0 }, │
480
+ │ const B = Type.Tuple([ │ │ { const: 1 }, │
481
+ | Type.Literal(2), │ │ { const: 2 }, │
482
+ | Type.Literal(3) │ │ { const: 3 } │
483
+ │ ]) │ │ ], │
484
+ │ const T = Type.Tuple([ │ │ additionalItems: false, │
485
+ | ...Type.Rest(A), │ │ minItems: 4, │
486
+ | ...Type.Rest(B) │ │ maxItems: 4 │
487
+ │ ]) │ │ } │
488
+ │ │ │ │
489
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
490
+ │ const T = Type.Object({ │ type T = { │ const R = { │
491
+ │ x: Type.Number(), │ x: number, │ $ref: 'T' │
492
+ │ y: Type.Number() │ y: number │ } │
493
+ │ }, { $id: 'T' }) | } │ │
494
+ │ │ │ │
495
+ │ const R = Type.Ref(T) │ type R = T │ │
496
+ │ │ │ │
497
+ │ │ │ │
498
+ │ │ │ │
499
+ │ │ │ │
500
+ └────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
501
+ ```
502
+
503
+ <a name='types-extended'></a>
504
+
505
+ ### Extended Types
506
+
507
+ TypeBox provides several extended types that can be used to produce schematics for common JavaScript constructs. These types can not 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 table lists the supported types.
508
+
509
+ ```typescript
510
+ ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
511
+ │ TypeBox │ TypeScript │ Extended Schema │
512
+ │ │ │ │
513
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
514
+ │ const T = Type.Constructor([ │ type T = new ( │ const T = { │
515
+ │ Type.String(), │ arg0: string, │ type: 'object', │
516
+ │ Type.Number() │ arg1: number │ instanceOf: 'Constructor', │
517
+ │ ], Type.Boolean()) │ ) => boolean │ parameters: [{ │
518
+ │ │ │ type: 'string' │
519
+ │ │ │ }, { │
520
+ │ │ │ type: 'number' │
521
+ │ │ │ }], │
522
+ │ │ │ return: { │
523
+ │ │ │ type: 'boolean' │
524
+ │ │ │ } │
525
+ │ │ │ } │
526
+ │ │ │ │
527
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
528
+ │ const T = Type.Function([ │ type T = ( │ const T = { │
529
+ | Type.String(), │ arg0: string, │ type : 'object', │
530
+ │ Type.Number() │ arg1: number │ instanceOf: 'Function', │
531
+ │ ], Type.Boolean()) │ ) => boolean │ parameters: [{ │
532
+ │ │ │ type: 'string' │
533
+ │ │ │ }, { │
534
+ │ │ │ type: 'number' │
535
+ │ │ │ }], │
536
+ │ │ │ return: { │
537
+ │ │ │ type: 'boolean' │
538
+ │ │ │ } │
539
+ │ │ │ } │
540
+ │ │ │ │
541
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
542
+ │ const T = Type.Promise( │ type T = Promise<string> │ const T = { │
543
+ │ Type.String() │ │ type: 'object', │
544
+ │ ) │ │ instanceOf: 'Promise', │
545
+ │ │ │ item: { │
546
+ │ │ │ type: 'string' │
547
+ │ │ │ } │
548
+ │ │ │ } │
549
+ │ │ │ │
550
+ │ │ │ │
551
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
552
+ │ const T = Type.Uint8Array() │ type T = Uint8Array │ const T = { │
553
+ │ │ │ type: 'object', │
554
+ │ │ │ instanceOf: 'Uint8Array' │
555
+ │ │ │ } │
556
+ │ │ │ │
557
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
558
+ │ const T = Type.Date() │ type T = Date │ const T = { │
559
+ │ │ │ type: 'object', │
560
+ │ │ │ instanceOf: 'Date' │
561
+ │ │ │ } │
562
+ │ │ │ │
563
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
564
+ │ const T = Type.Undefined() │ type T = undefined │ const T = { │
565
+ │ │ │ type: 'null', │
566
+ │ │ │ typeOf: 'Undefined' │
567
+ │ │ │ } │
568
+ │ │ │ │
569
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
570
+ │ const T = Type.RegEx(/foo/) │ type T = string │ const T = { │
571
+ │ │ │ type: 'string', │
572
+ │ │ │ pattern: 'foo' │
573
+ │ │ │ } │
574
+ │ │ │ │
575
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
576
+ │ const T = Type.Symbol() │ type T = symbol │ const T = { │
577
+ │ │ │ type: 'null', │
578
+ │ │ │ typeOf: 'Symbol' │
579
+ │ │ │ } │
580
+ │ │ │ │
581
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
582
+ │ const T = Type.BigInt() │ type T = bigint │ const T = { │
583
+ │ │ │ type: 'null', │
584
+ │ │ │ typeOf: 'BigInt' │
585
+ │ │ │ } │
586
+ │ │ │ │
587
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
588
+ │ const T = Type.Void() │ type T = void │ const T = { │
589
+ │ │ │ type: 'null' │
590
+ │ │ │ typeOf: 'Void' │
591
+ │ │ │ } │
592
+ │ │ │ │
593
+ └────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
594
+ ```
595
+
596
+ <a name='types-modifiers'></a>
597
+
598
+ ### Modifiers
599
+
600
+ TypeBox provides modifiers that allow schema properties to be statically inferred as `readonly` or `optional`. The following table shows the supported modifiers and how they map between TypeScript and JSON Schema.
601
+
602
+ ```typescript
603
+ ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
604
+ │ TypeBox │ TypeScript │ JSON Schema │
605
+ │ │ │ │
606
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
607
+ │ const T = Type.Object({ │ type T = { │ const T = { │
608
+ │ name: Type.Optional( │ name?: string │ type: 'object', │
609
+ │ Type.String() │ } │ properties: { │
610
+ │ ) │ │ name: { │
611
+ │ }) │ │ type: 'string' │
612
+ │ │ │ } │
613
+ │ │ │ } │
614
+ │ │ │ } │
615
+ │ │ │ │
616
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
617
+ │ const T = Type.Object({ │ type T = { │ const T = { │
618
+ │ name: Type.Readonly( │ readonly name: string │ type: 'object', │
619
+ │ Type.String() │ } │ properties: { │
620
+ │ ) │ │ name: { │
621
+ │ }) │ │ type: 'string' │
622
+ │ │ │ } │
623
+ │ │ │ }, │
624
+ │ │ │ required: ['name'] │
625
+ │ │ │ } │
626
+ │ │ │ │
627
+ ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
628
+ │ const T = Type.Object({ │ type T = { │ const T = { │
629
+ │ name: Type.ReadonlyOptional( │ readonly name?: string │ type: 'object', │
630
+ │ Type.String() │ } │ properties: { │
631
+ │ ) │ │ name: { │
632
+ │ }) │ │ type: 'string' │
633
+ │ │ │ } │
634
+ │ │ │ } │
635
+ │ │ │ } │
636
+ │ │ │ │
637
+ └────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘
638
+ ```
639
+
640
+ <a name='types-options'></a>
641
+
642
+ ### Options
643
+
644
+ You can pass JSON Schema options on the last argument of any type. Option hints specific to each type are provided for convenience.
645
+
646
+ ```typescript
647
+ // String must be an email
648
+ const T = Type.String({ // const T = {
649
+ format: 'email' // type: 'string',
650
+ }) // format: 'email'
651
+ // }
652
+
653
+ // Mumber must be a multiple of 2
654
+ const T = Type.Number({ // const T = {
655
+ multipleOf: 2 // type: 'number',
656
+ }) // multipleOf: 2
657
+ // }
658
+
659
+ // Array must have at least 5 integer values
660
+ const T = Type.Array(Type.Integer(), { // const T = {
661
+ minItems: 5 // type: 'array',
662
+ }) // minItems: 5,
663
+ // items: {
664
+ // type: 'integer'
665
+ // }
666
+ // }
667
+
668
+ ```
669
+
670
+ <a name='types-generics'></a>
671
+
672
+ ### Generic Types
673
+
674
+ Generic types can be created with generic functions constrained to type `TSchema`. The following creates a generic `Vector<T>` type.
675
+
676
+ ```typescript
677
+ import { Type, Static, TSchema } from '@sinclair/typebox'
678
+
679
+ const Vector = <T extends TSchema>(t: T) => Type.Object({ x: t, y: t, z: t })
680
+
681
+ const NumberVector = Vector(Type.Number()) // const NumberVector = {
682
+ // type: 'object',
683
+ // required: ['x', 'y', 'z'],
684
+ // properties: {
685
+ // x: { type: 'number' },
686
+ // y: { type: 'number' },
687
+ // z: { type: 'number' }
688
+ // }
689
+ // }
690
+
691
+ type NumberVector = Static<typeof NumberVector> // type NumberVector = {
692
+ // x: number,
693
+ // y: number,
694
+ // z: number
695
+ // }
696
+
697
+ const BooleanVector = Vector(Type.Boolean()) // const BooleanVector = {
698
+ // type: 'object',
699
+ // required: ['x', 'y', 'z'],
700
+ // properties: {
701
+ // x: { type: 'boolean' },
702
+ // y: { type: 'boolean' },
703
+ // z: { type: 'boolean' }
704
+ // }
705
+ // }
706
+
707
+ type BooleanVector = Static<typeof BooleanVector> // type BooleanVector = {
708
+ // x: boolean,
709
+ // y: boolean,
710
+ // z: boolean
711
+ // }
712
+ ```
713
+
714
+ The following creates a generic `Nullable<T>` type.
715
+
716
+ ```typescript
717
+ const Nullable = <T extends TSchema>(schema: T) => Type.Union([schema, Type.Null()])
718
+
719
+ const T = Nullable(Type.String()) // const T = {
720
+ // anyOf: [
721
+ // { type: 'string' },
722
+ // { type: 'null' }
723
+ // ]
724
+ // }
725
+
726
+ type T = Static<typeof T> // type T = string | null
727
+ ```
728
+
729
+ <a name='types-references'></a>
730
+
731
+ ### Reference Types
732
+
733
+ Reference types are supported with `Type.Ref`. The target type must specify a valid `$id`.
734
+
735
+ ```typescript
736
+ const T = Type.String({ $id: 'T' }) // const T = {
737
+ // $id: 'T',
738
+ // type: 'string'
739
+ // }
740
+
741
+ const R = Type.Ref(T) // const R = {
742
+ // $ref: 'T'
743
+ // }
744
+ ```
745
+
746
+ <a name='types-recursive'></a>
747
+
748
+ ### Recursive Types
749
+
750
+ Recursive types are supported with `Type.Recursive`
751
+
752
+ ```typescript
753
+ const Node = Type.Recursive(Node => Type.Object({ // const Node = {
754
+ id: Type.String(), // $id: 'Node',
755
+ nodes: Type.Array(Node) // type: 'object',
756
+ }), { $id: 'Node' }) // properties: {
757
+ // id: {
758
+ // type: 'string'
759
+ // },
760
+ // nodes: {
761
+ // type: 'array',
762
+ // items: {
763
+ // $ref: 'Node'
764
+ // }
765
+ // }
766
+ // },
767
+ // required: [
768
+ // 'id',
769
+ // 'nodes'
770
+ // ]
771
+ // }
772
+
773
+ type Node = Static<typeof Node> // type Node = {
774
+ // id: string
775
+ // nodes: Node[]
776
+ // }
777
+
778
+ function test(node: Node) {
779
+ const id = node.nodes[0].nodes[0].id // id is string
780
+ }
781
+ ```
782
+
783
+ <a name='types-conditional'></a>
784
+
785
+ ### Conditional Types
786
+
787
+ Conditional types are supported with `Type.Extends`, `Type.Exclude` and `Type.Extract`
788
+
789
+ ```typescript
790
+ // TypeScript
791
+
792
+ type T0 = string extends number ? true : false // type T0 = false
793
+
794
+ type T1 = Extract<string | number, number> // type T1 = number
795
+
796
+ type T2 = Exclude<string | number, number> // type T2 = string
797
+
798
+ // TypeBox
799
+
800
+ const T0 = Type.Extends(Type.String(), Type.Number(), Type.Literal(true), Type.Literal(false))
801
+
802
+ const T1 = Type.Extract(Type.Union([Type.String(), Type.Number()]), Type.Number())
803
+
804
+ const T2 = Type.Exclude(Type.Union([Type.String(), Type.Number()]), Type.Number())
805
+
806
+
807
+ type T0 = Static<typeof T0> // type T0 = false
808
+
809
+ type T1 = Static<typeof T1> // type T1 = number
810
+
811
+ type T2 = Static<typeof T2> // type T2 = string
812
+ ```
813
+
814
+ <a name='types-template-literal'></a>
815
+
816
+ ### Template Literal Types
817
+
818
+ TypeBox supports Template Literal types using `Type.TemplateLiteral`. These types can be created using a simple template DSL syntax, however more complex template literals can be created by passing an array of literal and union types. The examples below show the template DSL syntax.
819
+
820
+ ```typescript
821
+ // TypeScript
822
+
823
+ type P = `/post/${string}/user/${number}` // type P = `/post/${string}/user/${number}`
824
+
825
+ type T = `option${'A'|'B'}` // type T = 'optionA' | 'optionB'
826
+
827
+ type R = Record<T, string> // type R = {
828
+ // optionA: string
829
+ // optionB: string
830
+ // }
831
+
832
+ // TypeBox
833
+
834
+ const P = Type.TemplateLiteral('/post/${string}/user/${number}')
835
+
836
+ // const P = {
837
+ // type: 'string',
838
+ // pattern: '^/post/(.*)/user/(0|[1-9][0-9]*)$'
839
+ // }
840
+
841
+ const T = Type.TemplateLiteral('option${A|B}') // const T = {
842
+ // pattern: '^option(A|B)$',
843
+ // type: 'string'
844
+ // }
845
+
846
+ const R = Type.Record(T, Type.String()) // const R = {
847
+ // type: 'object',
848
+ // required: ['optionA', 'optionB'],
849
+ // properties: {
850
+ // optionA: {
851
+ // type: 'string'
852
+ // },
853
+ // optionB: {
854
+ // type: 'string'
855
+ // }
856
+ // }
857
+ // }
858
+ ```
859
+
860
+ <a name='types-indexed'></a>
861
+
862
+ ### Indexed Access Types
863
+
864
+ TypeBox supports Indexed Access types using `Type.Index`. This feature provides a consistent way to access property types without having to extract them from the underlying schema representation. Indexed accessors are supported for object and tuples, as well as nested union and intersect types.
865
+
866
+ ```typescript
867
+ const T = Type.Object({ // const T = {
868
+ x: Type.Number(), // type: 'object',
869
+ y: Type.String(), // required: ['x', 'y', 'z'],
870
+ z: Type.Boolean() // properties: {
871
+ }) // x: { type: 'number' },
872
+ // y: { type: 'string' },
873
+ // z: { type: 'string' }
874
+ // }
875
+ // }
876
+
877
+ const A = Type.Index(T, ['x']) // const A = { type: 'number' }
878
+
879
+ const B = Type.Index(T, ['x', 'y']) // const B = {
880
+ // anyOf: [
881
+ // { type: 'number' },
882
+ // { type: 'string' }
883
+ // ]
884
+ // }
885
+
886
+ const C = Type.Index(T, Type.KeyOf(T)) // const C = {
887
+ // anyOf: [
888
+ // { type: 'number' },
889
+ // { type: 'string' },
890
+ // { type: 'boolean' }
891
+ // ]
892
+ // }
893
+ ```
894
+
895
+ <a name='types-rest'></a>
896
+
897
+ ### Rest Types
898
+
899
+ Rest parameters are supported with `Type.Rest`. This function is used to extract interior type elements from tuples which enables them to compose with the JavaScript spread operator `...`. This type can be used for tuple concatenation as well as for variadic functions.
900
+
901
+ ```typescript
902
+ // TypeScript
903
+
904
+ type T = [number, number] // type T = [number, number]
905
+
906
+ type C = [...T, number] // type C = [number, number, number]
907
+
908
+ type F = (...param: C) => void // type F = (
909
+ // param0: number,
910
+ // param1: number,
911
+ // param2: number
912
+ // ) => void
913
+
914
+ // TypeBox
915
+
916
+ const T = Type.Tuple([ // const T: TTuple<[
917
+ Type.Number(), // TNumber,
918
+ Type.Number() // TNumber
919
+ ]) // ]>
920
+
921
+ const C = Type.Tuple([ // const C: TTuple<[
922
+ ...Type.Rest(T), // TNumber,
923
+ Type.Number() // TNumber,
924
+ ]) // TNumber
925
+ // ]>
926
+
927
+ const F = Type.Function(Type.Rest(C), Type.Void()) // const F: TFunction<[
928
+ // TNumber,
929
+ // TNumber,
930
+ // TNumber
931
+ // ], TVoid>
932
+ ```
933
+ <a name='types-unsafe'></a>
934
+
935
+ ### Unsafe Types
936
+
937
+ Use `Type.Unsafe` to create custom schematics with user defined inference rules.
938
+
939
+ ```typescript
940
+ const T = Type.Unsafe<string>({ type: 'number' }) // const T = {
941
+ // type: 'number'
942
+ // }
943
+
944
+ type T = Static<typeof T> // type T = string
945
+ ```
946
+
947
+ The `Type.Unsafe` type can be useful to express specific OpenAPI schema representations.
948
+
949
+ ```typescript
950
+ import { Type, Static, TSchema } from '@sinclair/typebox'
951
+
952
+ // Nullable<T>
953
+
954
+ function Nullable<T extends TSchema>(schema: T) {
955
+ return Type.Unsafe<Static<T> | null>({ ...schema, nullable: true })
956
+ }
957
+
958
+ const T = Nullable(Type.String()) // const T = {
959
+ // type: 'string',
960
+ // nullable: true
961
+ // }
962
+
963
+ type T = Static<typeof T> // type T = string | null
964
+
965
+ // StringEnum<string[]>
966
+
967
+ function StringEnum<T extends string[]>(values: [...T]) {
968
+ return Type.Unsafe<T[number]>({ type: 'string', enum: values })
969
+ }
970
+
971
+ const T = StringEnum(['A', 'B', 'C']) // const T = {
972
+ // enum: ['A', 'B', 'C']
973
+ // }
974
+
975
+ type T = Static<typeof T> // type T = 'A' | 'B' | 'C'
976
+ ```
977
+
978
+ <a name='types-guards'></a>
979
+
980
+ ### Type Guards
981
+
982
+ TypeBox provides a `TypeGuard` module that can be used for reflection and asserting values as types.
983
+
984
+ ```typescript
985
+ import { Type, TypeGuard } from '@sinclair/typebox'
986
+
987
+ const T = Type.String()
988
+
989
+ if(TypeGuard.TString(T)) {
990
+
991
+ // T is TString
992
+ }
993
+ ```
994
+
995
+ <a name='types-strict'></a>
996
+
997
+ ### Strict
998
+
999
+ TypeBox schemas contain the `Kind` and `Modifier` symbol properties. These properties are used for type composition and 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.
1000
+
1001
+ ```typescript
1002
+ const T = Type.Object({ // const T = {
1003
+ name: Type.Optional(Type.String()) // [Kind]: 'Object',
1004
+ }) // type: 'object',
1005
+ // properties: {
1006
+ // name: {
1007
+ // [Kind]: 'String',
1008
+ // type: 'string',
1009
+ // [Modifier]: 'Optional'
1010
+ // }
1011
+ // }
1012
+ // }
1013
+
1014
+ const U = Type.Strict(T) // const U = {
1015
+ // type: 'object',
1016
+ // properties: {
1017
+ // name: {
1018
+ // type: 'string'
1019
+ // }
1020
+ // }
1021
+ // }
1022
+ ```
1023
+
1024
+ <a name='values'></a>
1025
+
1026
+ ## Values
1027
+
1028
+ 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 optional import.
1029
+
1030
+ ```typescript
1031
+ import { Value } from '@sinclair/typebox/value'
1032
+ ```
1033
+
1034
+ <a name='values-create'></a>
1035
+
1036
+ ### Create
1037
+
1038
+ Use the Create function to create a value from a type. TypeBox will use default values if specified.
1039
+
1040
+ ```typescript
1041
+ const T = Type.Object({ x: Type.Number(), y: Type.Number({ default: 42 }) })
1042
+
1043
+ const A = Value.Create(T) // const A = { x: 0, y: 42 }
1044
+ ```
1045
+
1046
+ <a name='values-clone'></a>
1047
+
1048
+ ### Clone
1049
+
1050
+ Use the Clone function to deeply clone a value
1051
+
1052
+ ```typescript
1053
+ const A = Value.Clone({ x: 1, y: 2, z: 3 }) // const A = { x: 1, y: 2, z: 3 }
1054
+ ```
1055
+
1056
+ <a name='values-check'></a>
1057
+
1058
+ ### Check
1059
+
1060
+ Use the Check function to type check a value
1061
+
1062
+ ```typescript
1063
+ const T = Type.Object({ x: Type.Number() })
1064
+
1065
+ const R = Value.Check(T, { x: 1 }) // const R = true
1066
+ ```
1067
+
1068
+ <a name='values-convert'></a>
1069
+
1070
+ ### Convert
1071
+
1072
+ Use the Convert function to convert a value into its target type if a reasonable conversion is possible.
1073
+
1074
+ ```typescript
1075
+ const T = Type.Object({ x: Type.Number() })
1076
+
1077
+ const R1 = Value.Convert(T, { x: '3.14' }) // const R1 = { x: 3.14 }
1078
+
1079
+ const R2 = Value.Convert(T, { x: 'not a number' }) // const R2 = { x: 'not a number' }
1080
+ ```
1081
+
1082
+ <a name='values-cast'></a>
1083
+
1084
+ ### Cast
1085
+
1086
+ 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.
1087
+
1088
+ ```typescript
1089
+ const T = Type.Object({ x: Type.Number(), y: Type.Number() }, { additionalProperties: false })
1090
+
1091
+ const X = Value.Cast(T, null) // const X = { x: 0, y: 0 }
1092
+
1093
+ const Y = Value.Cast(T, { x: 1 }) // const Y = { x: 1, y: 0 }
1094
+
1095
+ const Z = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const Z = { x: 1, y: 2 }
1096
+ ```
1097
+
1098
+ <a name='values-equal'></a>
1099
+
1100
+ ### Equal
1101
+
1102
+ Use the Equal function to deeply check for value equality.
1103
+
1104
+ ```typescript
1105
+ const R = Value.Equal( // const R = true
1106
+ { x: 1, y: 2, z: 3 },
1107
+ { x: 1, y: 2, z: 3 }
1108
+ )
1109
+ ```
1110
+
1111
+ <a name='values-hash'></a>
1112
+
1113
+ ### Hash
1114
+
1115
+ Use the Hash function to create a [FNV1A-64](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function) non cryptographic hash of a value.
1116
+
1117
+ ```typescript
1118
+ const A = Value.Hash({ x: 1, y: 2, z: 3 }) // const A = 2910466848807138541n
1119
+
1120
+ const B = Value.Hash({ x: 1, y: 4, z: 3 }) // const B = 1418369778807423581n
1121
+ ```
1122
+
1123
+ <a name='values-diff'></a>
1124
+
1125
+ ### Diff
1126
+
1127
+ Use the Diff function to produce a sequence of edits to transform one value into another.
1128
+
1129
+ ```typescript
1130
+ const E = Value.Diff( // const E = [
1131
+ { x: 1, y: 2, z: 3 }, // { type: 'update', path: '/y', value: 4 },
1132
+ { y: 4, z: 5, w: 6 } // { type: 'update', path: '/z', value: 5 },
1133
+ ) // { type: 'insert', path: '/w', value: 6 },
1134
+ // { type: 'delete', path: '/x' }
1135
+ // ]
1136
+ ```
1137
+
1138
+ <a name='values-patch'></a>
1139
+
1140
+ ### Patch
1141
+
1142
+ Use the Patch function to apply edits
1143
+
1144
+ ```typescript
1145
+ const A = { x: 1, y: 2 }
1146
+
1147
+ const B = { x: 3 }
1148
+
1149
+ const E = Value.Diff(A, B) // const E = [
1150
+ // { type: 'update', path: '/x', value: 3 },
1151
+ // { type: 'delete', path: '/y' }
1152
+ // ]
1153
+
1154
+ const C = Value.Patch<typeof B>(A, E) // const C = { x: 3 }
1155
+ ```
1156
+
1157
+ <a name='values-errors'></a>
1158
+
1159
+ ### Errors
1160
+
1161
+ Use the Errors function enumerate validation errors.
1162
+
1163
+ ```typescript
1164
+ const T = Type.Object({ x: Type.Number(), y: Type.Number() })
1165
+
1166
+ const R = [...Value.Errors(T, { x: '42' })] // const R = [{
1167
+ // schema: { type: 'number' },
1168
+ // path: '/x',
1169
+ // value: '42',
1170
+ // message: 'Expected number'
1171
+ // }, {
1172
+ // schema: { type: 'number' },
1173
+ // path: '/y',
1174
+ // value: undefined,
1175
+ // message: 'Expected number'
1176
+ // }]
1177
+ ```
1178
+
1179
+ <a name='values-mutate'></a>
1180
+
1181
+ ### Mutate
1182
+
1183
+ Use the Mutate function to perform a deep mutable value assignment while retaining internal references.
1184
+
1185
+ ```typescript
1186
+ const Y = { z: 1 } // const Y = { z: 1 }
1187
+
1188
+ const X = { y: Y } // const X = { y: { z: 1 } }
1189
+
1190
+ const A = { x: X } // const A = { x: { y: { z: 1 } } }
1191
+
1192
+
1193
+ Value.Mutate(A, { x: { y: { z: 2 } } }) // const A' = { x: { y: { z: 2 } } }
1194
+
1195
+ const R0 = A.x.y.z === 2 // const R0 = true
1196
+
1197
+ const R1 = A.x.y === Y // const R1 = true
1198
+
1199
+ const R2 = A.x === X // const R2 = true
1200
+ ```
1201
+
1202
+ <a name='values-pointer'></a>
1203
+
1204
+ ### Pointer
1205
+
1206
+ Use ValuePointer to perform mutable updates on existing values using [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) JSON Pointers.
1207
+
1208
+ ```typescript
1209
+ import { ValuePointer } from '@sinclair/typebox/value'
1210
+
1211
+ const A = { x: 0, y: 0, z: 0 }
1212
+
1213
+ ValuePointer.Set(A, '/x', 1) // const A' = { x: 1, y: 0, z: 0 }
1214
+
1215
+ ValuePointer.Set(A, '/y', 1) // const A' = { x: 1, y: 1, z: 0 }
1216
+
1217
+ ValuePointer.Set(A, '/z', 1) // const A' = { x: 1, y: 1, z: 1 }
1218
+ ```
1219
+
1220
+ <a name='typecheck'></a>
1221
+
1222
+ ## TypeCheck
1223
+
1224
+ 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.
1225
+
1226
+ The following sections detail using Ajv and TypeBox's compiler infrastructure.
1227
+
1228
+ <a name='typecheck-ajv'></a>
1229
+
1230
+ ## Ajv
1231
+
1232
+ The following shows the recommended setup for Ajv.
1233
+
1234
+ ```bash
1235
+ $ npm install ajv ajv-formats --save
1236
+ ```
1237
+
1238
+ ```typescript
1239
+ import { Type } from '@sinclair/typebox'
1240
+ import addFormats from 'ajv-formats'
1241
+ import Ajv from 'ajv'
1242
+
1243
+ const ajv = addFormats(new Ajv({}), [
1244
+ 'date-time',
1245
+ 'time',
1246
+ 'date',
1247
+ 'email',
1248
+ 'hostname',
1249
+ 'ipv4',
1250
+ 'ipv6',
1251
+ 'uri',
1252
+ 'uri-reference',
1253
+ 'uuid',
1254
+ 'uri-template',
1255
+ 'json-pointer',
1256
+ 'relative-json-pointer',
1257
+ 'regex'
1258
+ ])
1259
+
1260
+ const C = ajv.compile(Type.Object({
1261
+ x: Type.Number(),
1262
+ y: Type.Number(),
1263
+ z: Type.Number()
1264
+ }))
1265
+
1266
+ const R = C({ x: 1, y: 2, z: 3 }) // const R = true
1267
+ ```
1268
+
1269
+ <a name='typecheck-typecompiler'></a>
1270
+
1271
+ ### TypeCompiler
1272
+
1273
+ 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.
1274
+
1275
+ The TypeCompiler is provided as an optional import.
1276
+
1277
+ ```typescript
1278
+ import { TypeCompiler } from '@sinclair/typebox/compiler'
1279
+ ```
1280
+
1281
+ Use the `Compile(...)` function to compile a type. Note that compilation is an expensive operation that should typically be performed once per type during application start up. TypeBox does not cache previously compiled types, so applications are expected to hold references to each compiled type for the lifetime of the application.
1282
+
1283
+ ```typescript
1284
+ const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{
1285
+ x: Type.Number(), // x: TNumber;
1286
+ y: Type.Number(), // y: TNumber;
1287
+ z: Type.Number() // z: TNumber;
1288
+ })) // }>>
1289
+
1290
+ const R = C.Check({ x: 1, y: 2, z: 3 }) // const R = true
1291
+ ```
1292
+
1293
+ 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.
1294
+
1295
+ ```typescript
1296
+ const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck<TObject<{
1297
+ x: Type.Number(), // x: TNumber;
1298
+ y: Type.Number(), // y: TNumber;
1299
+ z: Type.Number() // z: TNumber;
1300
+ })) // }>>
1301
+
1302
+ const value = { }
1303
+
1304
+ const errors = [...C.Errors(value)] // const errors = [{
1305
+ // schema: { type: 'number' },
1306
+ // path: '/x',
1307
+ // value: undefined,
1308
+ // message: 'Expected number'
1309
+ // }, {
1310
+ // schema: { type: 'number' },
1311
+ // path: '/y',
1312
+ // value: undefined,
1313
+ // message: 'Expected number'
1314
+ // }, {
1315
+ // schema: { type: 'number' },
1316
+ // path: '/z',
1317
+ // value: undefined,
1318
+ // message: 'Expected number'
1319
+ // }]
1320
+ ```
1321
+
1322
+ Compiled routines can be inspected with the `.Code()` function.
1323
+
1324
+ ```typescript
1325
+ const C = TypeCompiler.Compile(Type.String()) // const C: TypeCheck<TString>
1326
+
1327
+ console.log(C.Code()) // return function check(value) {
1328
+ // return (
1329
+ // (typeof value === 'string')
1330
+ // )
1331
+ // }
1332
+ ```
1333
+
1334
+ <a name='typesystem'></a>
1335
+
1336
+ ## TypeSystem
1337
+
1338
+ The TypeBox TypeSystem module provides functionality to define types above and beyond the Standard and Extended type sets as well as control various assertion policies. Configurations made to the TypeSystem module are observed by both `TypeCompiler` and `Value` modules.
1339
+
1340
+ The TypeSystem module is provided as an optional import.
1341
+
1342
+ ```typescript
1343
+ import { TypeSystem } from '@sinclair/typebox/system'
1344
+ ```
1345
+
1346
+ <a name='typesystem-types'></a>
1347
+
1348
+ ### Types
1349
+
1350
+ Use the `Type(...)` function to create custom types. This function lets you specify custom value assertion logic and will return a type factory function which is used to instance the type. This function accepts two generic arguments, the first is the inference type, the second is options used to constrain the type. The following creates a Vector type.
1351
+
1352
+ ```typescript
1353
+ type VectorOptions = { abs: boolean }
1354
+
1355
+ type Vector = { x: number, y: number }
1356
+
1357
+ const Vector = TypeSystem.Type<Vector, VectorOptions>('Vector', (options, value) => {
1358
+ return (
1359
+ typeof value === 'object' && value !== null &&
1360
+ 'x' in value && typeof value.x === 'number' &&
1361
+ 'y' in value && typeof value.y === 'number' &&
1362
+ (options.abs ? (value.x === Math.abs(value.x) && value.y === Math.abs(value.y)) : true)
1363
+ )
1364
+ })
1365
+
1366
+ const T = Vector({ abs: true })
1367
+
1368
+ type T = Static<typeof T> // type T = Vector
1369
+
1370
+ const R1 = Value.Check(T, { x: 1, y: 1 }) // const R1 = true
1371
+
1372
+ const R2 = Value.Check(T, { x: 1, y: '1' }) // const R2 = false
1373
+
1374
+ const R3 = Value.Check(T, { x: 1, y: -1 }) // const R3 = false
1375
+ ```
1376
+
1377
+ <a name='typesystem-formats'></a>
1378
+
1379
+ ### Formats
1380
+
1381
+ Use the `Format(...)` function to create a custom string format. The following creates a format that checks for lowercase strings.
1382
+
1383
+ ```typescript
1384
+ TypeSystem.Format('lowercase', value => value === value.toLowerCase()) // format should be lowercase
1385
+
1386
+ const T = Type.String({ format: 'lowercase' })
1387
+
1388
+ const A = Value.Check(T, 'Hello') // const A = false
1389
+
1390
+ const B = Value.Check(T, 'hello') // const B = true
1391
+ ```
1392
+
1393
+ <a name='typesystem-policies'></a>
1394
+
1395
+ ### Policies
1396
+
1397
+ TypeBox validates using standard JSON Schema assertion policies by default. It is possible to override some of these policies to have TypeBox assert inline with TypeScript static assertion rules. The following policy overrides are available.
1398
+
1399
+ ```typescript
1400
+ // Disallow undefined values for optional properties (default is false)
1401
+ //
1402
+ // const A: { x?: number } = { x: undefined } - disallowed when enabled
1403
+
1404
+ TypeSystem.ExactOptionalPropertyTypes = true
1405
+
1406
+ // Allow arrays to validate as object types (default is false)
1407
+ //
1408
+ // const A: {} = [] - allowed in TS
1409
+
1410
+ TypeSystem.AllowArrayObjects = true
1411
+
1412
+ // Allow numeric values to be NaN or + or - Infinity (default is false)
1413
+ //
1414
+ // const A: number = NaN - allowed in TS
1415
+
1416
+ TypeSystem.AllowNaN = true
1417
+ ```
1418
+
1419
+ <a name='workbench'></a>
1420
+
1421
+ ## Workbench
1422
+
1423
+ TypeBox offers a small web based code generation tool that can be used to convert TypeScript types into TypeBox type definitions as well as a variety of other formats.
1424
+
1425
+ [Workbench Link Here](https://sinclairzx81.github.io/typebox-workbench/)
1426
+
1427
+ <div align='center'>
1428
+
1429
+ <a href="https://sinclairzx81.github.io/typebox-workbench/"><img src="https://github.com/sinclairzx81/typebox/blob/master/workbench.png?raw=true" /></a>
1430
+
1431
+ </div>
1432
+
1433
+ <a name='ecosystem'></a>
1434
+
1435
+ ## Ecosystem
1436
+
1437
+ The following is a list of community packages that provide general tooling and framework support for TypeBox.
1438
+
1439
+ | Package | Description |
1440
+ | ------------- | ------------- |
1441
+ | [elysia](https://github.com/elysiajs/elysia) | Fast and friendly Bun web framework |
1442
+ | [fastify-type-provider-typebox](https://github.com/fastify/fastify-type-provider-typebox) | Fastify TypeBox integration with the Fastify Type Provider |
1443
+ | [fetch-typebox](https://github.com/erfanium/fetch-typebox) | Drop-in replacement for fetch that brings easy integration with TypeBox |
1444
+ | [schema2typebox](https://github.com/xddq/schema2typebox) | Creating TypeBox code from JSON schemas |
1445
+ | [ts2typebox](https://github.com/xddq/ts2typebox) | Creating TypeBox code from Typescript types |
1446
+
1447
+ <a name='benchmark'></a>
1448
+
1449
+ ## Benchmark
1450
+
1451
+ 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.0.0.
1452
+
1453
+ For additional comparative benchmarks, please refer to [typescript-runtime-type-benchmarks](https://moltar.github.io/typescript-runtime-type-benchmarks/).
1454
+
1455
+ <a name='benchmark-compile'></a>
1456
+
1457
+ ### Compile
1458
+
1459
+ This benchmark measures compilation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/compile.ts).
1460
+
1461
+ ```typescript
1462
+ ┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┐
1463
+ │ (index) │ Iterations │ Ajv │ TypeCompiler │ Performance │
1464
+ ├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┤
1465
+ │ Literal_String │ 1000 │ ' 220 ms' │ ' 6 ms' │ ' 36.67 x' │
1466
+ │ Literal_Number │ 1000 │ ' 172 ms' │ ' 4 ms' │ ' 43.00 x' │
1467
+ │ Literal_Boolean │ 1000 │ ' 162 ms' │ ' 4 ms' │ ' 40.50 x' │
1468
+ │ Primitive_Number │ 1000 │ ' 161 ms' │ ' 6 ms' │ ' 26.83 x' │
1469
+ │ Primitive_String │ 1000 │ ' 154 ms' │ ' 4 ms' │ ' 38.50 x' │
1470
+ │ Primitive_String_Pattern │ 1000 │ ' 204 ms' │ ' 10 ms' │ ' 20.40 x' │
1471
+ │ Primitive_Boolean │ 1000 │ ' 131 ms' │ ' 4 ms' │ ' 32.75 x' │
1472
+ │ Primitive_Null │ 1000 │ ' 142 ms' │ ' 5 ms' │ ' 28.40 x' │
1473
+ │ Object_Unconstrained │ 1000 │ ' 1263 ms' │ ' 29 ms' │ ' 43.55 x' │
1474
+ │ Object_Constrained │ 1000 │ ' 1267 ms' │ ' 24 ms' │ ' 52.79 x' │
1475
+ │ Object_Vector3 │ 1000 │ ' 382 ms' │ ' 7 ms' │ ' 54.57 x' │
1476
+ │ Object_Box3D │ 1000 │ ' 1723 ms' │ ' 28 ms' │ ' 61.54 x' │
1477
+ │ Tuple_Primitive │ 1000 │ ' 495 ms' │ ' 13 ms' │ ' 38.08 x' │
1478
+ │ Tuple_Object │ 1000 │ ' 1271 ms' │ ' 16 ms' │ ' 79.44 x' │
1479
+ │ Composite_Intersect │ 1000 │ ' 656 ms' │ ' 19 ms' │ ' 34.53 x' │
1480
+ │ Composite_Union │ 1000 │ ' 529 ms' │ ' 18 ms' │ ' 29.39 x' │
1481
+ │ Math_Vector4 │ 1000 │ ' 802 ms' │ ' 14 ms' │ ' 57.29 x' │
1482
+ │ Math_Matrix4 │ 1000 │ ' 411 ms' │ ' 6 ms' │ ' 68.50 x' │
1483
+ │ Array_Primitive_Number │ 1000 │ ' 369 ms' │ ' 6 ms' │ ' 61.50 x' │
1484
+ │ Array_Primitive_String │ 1000 │ ' 369 ms' │ ' 4 ms' │ ' 92.25 x' │
1485
+ │ Array_Primitive_Boolean │ 1000 │ ' 297 ms' │ ' 3 ms' │ ' 99.00 x' │
1486
+ │ Array_Object_Unconstrained │ 1000 │ ' 1582 ms' │ ' 20 ms' │ ' 79.10 x' │
1487
+ │ Array_Object_Constrained │ 1000 │ ' 1629 ms' │ ' 19 ms' │ ' 85.74 x' │
1488
+ │ Array_Tuple_Primitive │ 1000 │ ' 652 ms' │ ' 12 ms' │ ' 54.33 x' │
1489
+ │ Array_Tuple_Object │ 1000 │ ' 1587 ms' │ ' 16 ms' │ ' 99.19 x' │
1490
+ │ Array_Composite_Intersect │ 1000 │ ' 1051 ms' │ ' 15 ms' │ ' 70.07 x' │
1491
+ │ Array_Composite_Union │ 1000 │ ' 733 ms' │ ' 15 ms' │ ' 48.87 x' │
1492
+ │ Array_Math_Vector4 │ 1000 │ ' 1071 ms' │ ' 12 ms' │ ' 89.25 x' │
1493
+ │ Array_Math_Matrix4 │ 1000 │ ' 636 ms' │ ' 5 ms' │ ' 127.20 x' │
1494
+ └────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┘
1495
+ ```
1496
+
1497
+ <a name='benchmark-validate'></a>
1498
+
1499
+ ### Validate
1500
+
1501
+ This benchmark measures validation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/check.ts).
1502
+
1503
+ ```typescript
1504
+ ┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐
1505
+ │ (index) │ Iterations │ ValueCheck │ Ajv │ TypeCompiler │ Performance │
1506
+ ├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
1507
+ │ Literal_String │ 1000000 │ ' 24 ms' │ ' 5 ms' │ ' 5 ms' │ ' 1.00 x' │
1508
+ │ Literal_Number │ 1000000 │ ' 21 ms' │ ' 17 ms' │ ' 9 ms' │ ' 1.89 x' │
1509
+ │ Literal_Boolean │ 1000000 │ ' 18 ms' │ ' 18 ms' │ ' 9 ms' │ ' 2.00 x' │
1510
+ │ Primitive_Number │ 1000000 │ ' 25 ms' │ ' 18 ms' │ ' 9 ms' │ ' 2.00 x' │
1511
+ │ Primitive_String │ 1000000 │ ' 25 ms' │ ' 17 ms' │ ' 9 ms' │ ' 1.89 x' │
1512
+ │ Primitive_String_Pattern │ 1000000 │ ' 174 ms' │ ' 44 ms' │ ' 36 ms' │ ' 1.22 x' │
1513
+ │ Primitive_Boolean │ 1000000 │ ' 22 ms' │ ' 17 ms' │ ' 9 ms' │ ' 1.89 x' │
1514
+ │ Primitive_Null │ 1000000 │ ' 22 ms' │ ' 16 ms' │ ' 9 ms' │ ' 1.78 x' │
1515
+ │ Object_Unconstrained │ 1000000 │ ' 1065 ms' │ ' 33 ms' │ ' 25 ms' │ ' 1.32 x' │
1516
+ │ Object_Constrained │ 1000000 │ ' 1192 ms' │ ' 53 ms' │ ' 38 ms' │ ' 1.39 x' │
1517
+ │ Object_Vector3 │ 1000000 │ ' 410 ms' │ ' 23 ms' │ ' 14 ms' │ ' 1.64 x' │
1518
+ │ Object_Box3D │ 1000000 │ ' 1939 ms' │ ' 54 ms' │ ' 50 ms' │ ' 1.08 x' │
1519
+ │ Object_Recursive │ 1000000 │ ' 5248 ms' │ ' 355 ms' │ ' 149 ms' │ ' 2.38 x' │
1520
+ │ Tuple_Primitive │ 1000000 │ ' 163 ms' │ ' 21 ms' │ ' 13 ms' │ ' 1.62 x' │
1521
+ │ Tuple_Object │ 1000000 │ ' 737 ms' │ ' 29 ms' │ ' 20 ms' │ ' 1.45 x' │
1522
+ │ Composite_Intersect │ 1000000 │ ' 761 ms' │ ' 24 ms' │ ' 15 ms' │ ' 1.60 x' │
1523
+ │ Composite_Union │ 1000000 │ ' 519 ms' │ ' 23 ms' │ ' 13 ms' │ ' 1.77 x' │
1524
+ │ Math_Vector4 │ 1000000 │ ' 247 ms' │ ' 21 ms' │ ' 11 ms' │ ' 1.91 x' │
1525
+ │ Math_Matrix4 │ 1000000 │ ' 1045 ms' │ ' 39 ms' │ ' 27 ms' │ ' 1.44 x' │
1526
+ │ Array_Primitive_Number │ 1000000 │ ' 256 ms' │ ' 20 ms' │ ' 12 ms' │ ' 1.67 x' │
1527
+ │ Array_Primitive_String │ 1000000 │ ' 222 ms' │ ' 21 ms' │ ' 14 ms' │ ' 1.50 x' │
1528
+ │ Array_Primitive_Boolean │ 1000000 │ ' 149 ms' │ ' 22 ms' │ ' 16 ms' │ ' 1.38 x' │
1529
+ │ Array_Object_Unconstrained │ 1000000 │ ' 5473 ms' │ ' 67 ms' │ ' 59 ms' │ ' 1.14 x' │
1530
+ │ Array_Object_Constrained │ 1000000 │ ' 5548 ms' │ ' 130 ms' │ ' 116 ms' │ ' 1.12 x' │
1531
+ │ Array_Object_Recursive │ 1000000 │ ' 21047 ms' │ ' 1710 ms' │ ' 584 ms' │ ' 2.93 x' │
1532
+ │ Array_Tuple_Primitive │ 1000000 │ ' 691 ms' │ ' 35 ms' │ ' 29 ms' │ ' 1.21 x' │
1533
+ │ Array_Tuple_Object │ 1000000 │ ' 3075 ms' │ ' 63 ms' │ ' 50 ms' │ ' 1.26 x' │
1534
+ │ Array_Composite_Intersect │ 1000000 │ ' 3126 ms' │ ' 44 ms' │ ' 35 ms' │ ' 1.26 x' │
1535
+ │ Array_Composite_Union │ 1000000 │ ' 2086 ms' │ ' 68 ms' │ ' 33 ms' │ ' 2.06 x' │
1536
+ │ Array_Math_Vector4 │ 1000000 │ ' 1069 ms' │ ' 38 ms' │ ' 23 ms' │ ' 1.65 x' │
1537
+ │ Array_Math_Matrix4 │ 1000000 │ ' 4559 ms' │ ' 111 ms' │ ' 88 ms' │ ' 1.26 x' │
1538
+ └────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘
1539
+ ```
1540
+
1541
+ <a name='benchmark-compression'></a>
1542
+
1543
+ ### Compression
1544
+
1545
+ The following table lists esbuild compiled and minified sizes for each TypeBox module.
1546
+
1547
+ ```typescript
1548
+ ┌──────────────────────┬────────────┬────────────┬─────────────┐
1549
+ │ (index) │ Compiled │ Minified │ Compression │
1550
+ ├──────────────────────┼────────────┼────────────┼─────────────┤
1551
+ │ typebox/compiler │ '128.0 kb' │ ' 57.0 kb' │ '2.25 x' │
1552
+ │ typebox/errors │ '111.6 kb' │ ' 49.1 kb' │ '2.27 x' │
1553
+ │ typebox/system │ ' 77.0 kb' │ ' 31.5 kb' │ '2.45 x' │
1554
+ │ typebox/value │ '177.7 kb' │ ' 76.8 kb' │ '2.31 x' │
1555
+ │ typebox │ ' 75.9 kb' │ ' 31.0 kb' │ '2.45 x' │
1556
+ └──────────────────────┴────────────┴────────────┴─────────────┘
1557
+ ```
1558
+
1559
+ <a name='contribute'></a>
1560
+
1561
+ ## Contribute
1562
+
1563
+ 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.