Coder Social home page Coder Social logo

typebox's Introduction

TypeBox

Json Schema Type Builder with Static Type Resolution for TypeScript



npm version Downloads Build License

Install

$ npm install @sinclair/typebox --save

Example

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

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

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

Overview

TypeBox is a runtime type builder that creates in-memory Json Schema objects that infer as TypeScript types. The schematics produced by this library are designed to match the static type checking rules of the TypeScript compiler. TypeBox offers a unified type that can be statically checked by TypeScript and runtime asserted using standard Json Schema validation.

This library is designed to allow Json Schema to compose similar to how types compose within TypeScript's type system. It can be used as a simple tool to build up complex schematics or integrated into REST and RPC services to help validate data received over the wire.

License MIT

Contents

Usage

The following shows general usage.

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

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

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

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

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

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

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

//--------------------------------------------------------------------------------------------
//
// ... then use the type both as Json Schema and as a TypeScript type.
//
//--------------------------------------------------------------------------------------------

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

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

  if(Value.Check(T, value)) {                        // ... as a Json Schema

    // ok...
  }
}

Types

TypeBox types are Json Schema fragments that compose into more complex types. Each fragment is structured such that any Json Schema compliant validator can runtime assert a value the same way TypeScript will statically assert a type. TypeBox offers a set of Json Types which are used to create Json Schema compliant schematics as well as a JavaScript type set used to create schematics for constructs native to JavaScript.

Json Types

The following table lists the supported Json types. These types are fully compatible with the Json Schema Draft 7 specification.

┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
 TypeBox                         TypeScript                   Json Schema                    
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Any()            type T = any                 const T = { }                  
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Unknown()        type T = unknown             const T = { }                  
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.String()         type T = string              const T = {                    
                                                                type: 'string'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Number()         type T = number              const T = {                    
                                                                type: 'number'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Integer()        type T = number              const T = {                    
                                                                type: 'integer'              
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Boolean()        type T = boolean             const T = {                    
                                                                type: 'boolean'              
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Null()           type T = null                const T = {                    
                                                                type: 'null'                 
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Literal(42)      type T = 42                  const T = {                    
                                                                const: 42,                   
                                                                type: 'number'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Array(           type T = number[]            const T = {                    
   Type.Number()                                                type: 'array',               
 )                                                              items: {                     
                                                                  type: 'number'             
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Object({         type T = {const T = {                    
   x: Type.Number(),               x: number,                   type: 'object',              
   y: Type.Number()                y: number                    required: ['x', 'y'], })                              }                              properties: {                
                                                                  x: {                       
                                                                    type: 'number'           
                                                                  },                         
                                                                  y: {                       
                                                                    type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Tuple([          type T = [number, number]    const T = {                    
   Type.Number(),                                               type: 'array',               
   Type.Number()                                                items: [{                    
 ])                                                               type: 'number'             
                                                                }, {                         
                                                                  type: 'number'             
                                                                }],                          
                                                                additionalItems: false,      
                                                                minItems: 2,                 
                                                                maxItems: 2                  
                                                              }                              
                                                                                             
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 enum Foo {                      enum Foo {                   const T = {                    
   A,                              A,                           anyOf: [{                    
   B                               B                              type: 'number', }                               }                                const: 0                   
                                                                }, { const T = Type.Enum(Foo)        type T = Foo                     type: 'number',            
                                                                  const: 1                   
                                                                }]                           
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Const({          type T = {const T = {                    
   x: 1,                           readonly x: 1,               type: 'object',              
   y: 2,                           readonly y: 2                required: ['x', 'y'], } as const)                     }                              properties: {                
                                                                  x: {                       
                                                                    type: 'number',          
                                                                    const: 1                 
                                                                  },                         
                                                                  y: {                       
                                                                    type: 'number',          
                                                                    const: 2                 
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.KeyOf(           type T = keyof {             const T = {                    
   Type.Object({                   x: number,                   anyOf: [{                    
     x: Type.Number(),             y: number                      type: 'string',            
     y: Type.Number()            }                                const: 'x'                 
   })                                                           }, {                         
 )                                                                type: 'string',            
                                                                  const: 'y'                 
                                                                }]                           
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Union([          type T = string | number     const T = {                    
   Type.String(),                                               anyOf: [{                    
   Type.Number()                                                  type: 'string'             
 ])                                                             }, {                         
                                                                  type: 'number'             
                                                                }]                           
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Intersect([      type T = {                   const T = {                    
   Type.Object({                   x: number                    allOf: [{                    
     x: Type.Number()            } & {                            type: 'object',   }),                             y: number                      required: ['x'],           
   Type.Object({}                                properties: {              
     y: Type.Number()                                               x: {                     
   ])                                                                 type: 'number'         
 ])                                                                 }                        
                                                                  }                          
                                                                }, {                         
                                                                  type: 'object',            |
                                                                  required: ['y'],           
                                                                  properties: {              
                                                                    y: {                     
                                                                      type: 'number'         
                                                                    }                        
                                                                  }                          
                                                                }]                           
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Composite([      type T = {                   const T = {                    
   Type.Object({                   x: number,                   type: 'object',              
     x: Type.Number()              y: number                    required: ['x', 'y'],        
   }),                           }                              properties: {                
   Type.Object({                                                  x: {                       
     y: Type.Number()                                               type: 'number'           
   })                                                             },                         
 ])                                                               y: {                       
                                                                    type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Never()          type T = never               const T = {                    
                                                                not: {}                      
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Not(            | type T = unknown             const T = {                    
   Type.String()                                                not: {                       
 )                                                                type: 'string'             
                                                                }                            
                                                              }                              
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Extends(         type T =                     const T = {                    
   Type.String(),                 string extends number         const: false,                
   Type.Number(),                   ? true                      type: 'boolean'              
   Type.Literal(true),              : false                   }                              
   Type.Literal(false)                                                                       
 )                                                                                           
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Extract(         type T = Extract<            const T = {                    
   Type.Union([                    string | number,             type: 'string'               
     Type.String(),                string                     }                              
     Type.Number(),              >                                                           
   ]),                                                                                       
   Type.String()                                                                             
 )                                                                                           
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Exclude(         type T = Exclude<            const T = {                    
   Type.Union([                    string | number,             type: 'number'               
     Type.String(),                string                     }                              
     Type.Number(),              >                                                           
   ]),                                                                                       
   Type.String()                                                                             
 )                                                                                           
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Mapped(          type T = {                   const T = {                    
   Type.Union([                    [_ in 'x' | 'y'] : number    type: 'object',              
     Type.Literal('x'),          }                              required: ['x', 'y'],        
     Type.Literal('y')                                          properties: {                
   ]),                                                            x: {                       
   () => Type.Number()                                              type: 'number'           
 )                                                                },                         
                                                                  y: {                       
                                                                    type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const U = Type.Union([          type U = 'open' | 'close'    const T = {                    
   Type.Literal('open'),                                        type: 'string',              
   Type.Literal('close')         type T = `on${U}`              pattern: '^on(open|close)$'  
 ])                                                           }                              
                                                                                             
 const T = Type                                                                              
   .TemplateLiteral([                                                                        
      Type.Literal('on'),                                                                    
      U                                                                                      
   ])                                                                                        
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Record(          type T = Record<             const T = {                    
   Type.String(),                  string,                      type: 'object',              
   Type.Number()                   number                       patternProperties: {         
 )                               >                                '^.*$': {                  
                                                                    type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Partial(         type T = Partial<{           const T = {                    
   Type.Object({                   x: number,                   type: 'object',              
     x: Type.Number(),             y: number                    properties: {                
     y: Type.Number()           | }>                               x: {                       
   })                                                               type: 'number'           
 )                                                                },                         
                                                                  y: {                       
                                                                    type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Required(        type T = Required<{          const T = {                    
   Type.Object({                   x?: number,                  type: 'object',              
     x: Type.Optional(             y?: number                   required: ['x', 'y'],        
       Type.Number()            | }>                             properties: {                
     ),                                                           x: {                       
     y: Type.Optional(                                              type: 'number'           
       Type.Number()                                              },                         
     )                                                            y: {                       
   })                                                               type: 'number'           
 )                                                                }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Pick(            type T = Pick<{              const T = {                    
   Type.Object({                   x: number,                   type: 'object',              
     x: Type.Number(),             y: number                    required: ['x'],             
     y: Type.Number()            }, 'x'>                        properties: {                
   }), ['x']                    |                                  x: {                       
 )                                                                  type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Omit(            type T = Omit<{              const T = {                    
   Type.Object({                   x: number,                   type: 'object',              
     x: Type.Number(),             y: number                    required: ['y'],             
     y: Type.Number()            }, 'x'>                        properties: {                
   }), ['x']                    |                                  y: {                       
 )                                                                  type: 'number'           
                                                                  }                          
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Index(           type T = {                   const T = {                    
   Type.Object({                   x: number,                   type: 'number'               
     x: Type.Number(),             y: string                  }                              
     y: Type.String()            }['x']                                                      
   }), ['x']                                                                                 
 )                                                                                           
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const A = Type.Tuple([          type A = [0, 1]              const T = {                    
   Type.Literal(0),              type B = [2, 3]                type: 'array',               
   Type.Literal(1)               type T = [                     items: [                     
 ])                                ...A,                          { const: 0 },              
 const B = Type.Tuple([            ...B                           { const: 1 },              
|   Type.Literal(2),              ]                                { const: 2 },              
|   Type.Literal(3)                                                { const: 3 }               
 ])                                                             ],                           
 const T = Type.Tuple([                                         additionalItems: false,      
|   ...Type.Rest(A),                                             minItems: 4,                 
|   ...Type.Rest(B)                                              maxItems: 4                  
 ])                                                           }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Uncapitalize(    type T = Uncapitalize<       const T = {                    
   Type.Literal('Hello')           'Hello'                      type: 'string',              
 )                               >                              const: 'hello'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Capitalize(      type T = Capitalize<         const T = {                    
   Type.Literal('hello')           'hello'                      type: 'string',              
 )                               >                              const: 'Hello'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Uppercase(       type T = Uppercase<          const T = {                    
   Type.Literal('hello')           'hello'                      type: 'string',              
 )                               >                              const: 'HELLO'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Lowercase(       type T = Lowercase<          const T = {                    
   Type.Literal('HELLO')           'HELLO'                      type: 'string',              
 )                               >                              const: 'hello'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Object({         type T = {const R = {                    
    x: Type.Number(),              x: number,                   $ref: 'T'                    
    y: Type.Number()               y: number                  }                              
 }, { $id: 'T' })               | }                                                           
                                                                                             
 const R = Type.Ref(T)           type R = T                                                  
                                                                                             
                                                                                             
                                                                                             
                                                                                             
└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘

JavaScript Types

TypeBox provides an extended type set that can be used to create schematics for common JavaScript constructs. These types can not be used with any standard Json Schema validator; but can be used to frame schematics for interfaces that may receive Json validated data. JavaScript types are prefixed with the [JavaScript] jsdoc comment for convenience. The following table lists the supported types.

┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
 TypeBox                         TypeScript                   Extended Schema                
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Constructor([    type T = new (               const T = {                    
   Type.String(),                 arg0: string,                 type: 'Constructor',         
   Type.Number()                  arg0: number                  parameters: [{               
 ], Type.Boolean())              ) => boolean                     type: 'string'             
                                                                }, {                         
                                                                  type: 'number'             
                                                                }],                          
                                                                returns: {                   
                                                                  type: 'boolean'            
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Function([       type T = (                   const T = {                    
|   Type.String(),                 arg0: string,                 type: 'Function',            
   Type.Number()                  arg1: number                  parameters: [{               
 ], Type.Boolean())              ) => boolean                     type: 'string'             
                                                                }, {                         
                                                                  type: 'number'             
                                                                }],                          
                                                                returns: {                   
                                                                  type: 'boolean'            
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Promise(         type T = Promise<string>     const T = {                    
   Type.String()                                                type: 'Promise',             
 )                                                              item: {                      
                                                                  type: 'string'             
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T =                       type T =                     const T = {                    
   Type.AsyncIterator(             AsyncIterableIterator<       type: 'AsyncIterator',       
     Type.String()                  string                      items: {                     
   )                               >                              type: 'string'             
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Iterator(        type T =                     const T = {                    
   Type.String()                   IterableIterator<string>     type: 'Iterator',            
 )                                                              items: {                     
                                                                  type: 'string'             
                                                                }                            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.RegExp(/abc/i)   type T = string              const T = {                    
                                                                type: 'RegExp'               
                                                                source: 'abc'                
                                                                flags: 'i'                   
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Uint8Array()     type T = Uint8Array          const T = {                    
                                                                type: 'Uint8Array'           
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Date()           type T = Date                const T = {                    
                                                                type: 'Date'                 
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Undefined()      type T = undefined           const T = {                    
                                                                type: 'undefined'            
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Symbol()         type T = symbol              const T = {                    
                                                                type: 'symbol'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.BigInt()         type T = bigint              const T = {                    
                                                                type: 'bigint'               
                                                              }                              
                                                                                             
├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
 const T = Type.Void()           type T = void                const T = {                    
                                                                type: 'void'                 
                                                              }                              
                                                                                             
└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘

Import

Import the Type namespace to bring in the full TypeBox type system. This is recommended for most users.

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

You can also selectively import types. This enables modern bundlers to tree shake for unused types.

import { Object, Number, String, Boolean, type Static } from '@sinclair/typebox'

Options

You can pass Json Schema options on the last argument of any given type. Option hints specific to each type are provided for convenience.

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

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

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

Properties

Object properties can be modified with Readonly and Optional. The following table shows how these modifiers map between TypeScript and Json Schema.

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

Generic Types

Generic types can be created with functions. TypeBox types extend the TSchema interface so you should constrain parameters to this type. The following creates a generic Vector type.

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

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

const NumberVector = Vector(Type.Number())           // type NumberVector = Vector<number>

Generic types are often used to create aliases for complex types. The following creates a Nullable generic type.

const Nullable = <T extends TSchema>(schema: T) => Type.Union([schema, Type.Null()])

const T = Nullable(Type.String())                    // const T = {
                                                     //   anyOf: [
                                                     //     { type: 'string' },
                                                     //     { type: 'null' }
                                                     //   ]
                                                     // }

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

Reference Types

Reference types can be created with Ref. These types infer the same as the target type but only store a named $ref to the target type.

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

const VectorRef = Type.Ref(Vector)                   // const VectorRef = {
                                                     //   $ref: 'Vector'
                                                     // }

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

Use Deref to dereference a type. This function will replace any interior reference with the target type.

const Vertex = Type.Object({                         // const Vertex = {
  position: VectorRef,                               //   type: 'object',
  texcoord: VectorRef,                               //   required: ['position', 'texcoord'],
})                                                   //   properties: {
                                                     //     position: { $ref: 'Vector' },
                                                     //     texcoord: { $ref: 'Vector' }
                                                     //   }
                                                     // }

const VertexDeref = Type.Deref(Vertex, [Vector])     // const VertexDeref = {
                                                     //   type: 'object',
                                                     //   required: ['position', 'texcoord'],
                                                     //   properties: {
                                                     //     position: {
                                                     //       type: 'object',
                                                     //       required: ['x', 'y', 'z'],
                                                     //       properties: {
                                                     //         x: { type: 'number' },
                                                     //         y: { type: 'number' }
                                                     //       }
                                                     //     },
                                                     //     texcoord: {
                                                     //       type: 'object',
                                                     //       required: ['x', 'y', 'z'],
                                                     //       properties: {
                                                     //         x: { type: 'number' },
                                                     //         y: { type: 'number' }
                                                     //       }
                                                     //     }
                                                     //   }
                                                     // }

Note that Ref types do not store structural information about the type they're referencing. Because of this, these types cannot be used with some mapping types (such as Partial or Pick). For applications that require mapping on Ref, use Deref to normalize the type first.

Recursive Types

TypeBox supports recursive data structures with Recursive. This type wraps an interior type and provides it a this context that allows the type to reference itself. The following creates a recursive type. Singular recursive inference is also supported.

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

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

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

Template Literal Types

TypeBox supports template literal types with the TemplateLiteral function. This type can be created using a syntax similar to the TypeScript template literal syntax or composed from exterior types. TypeBox encodes template literals as regular expressions which enables the template to be checked by Json Schema validators. This type also supports regular expression parsing that enables template patterns to be used for generative types. The following shows both TypeScript and TypeBox usage.

// TypeScript

type K = `prop${'A'|'B'|'C'}`                        // type T = 'propA' | 'propB' | 'propC'

type R = Record<K, string>                           // type R = {
                                                     //   propA: string
                                                     //   propB: string
                                                     //   propC: string
                                                     // }

// TypeBox

const K = Type.TemplateLiteral('prop${A|B|C}')       // const K: TTemplateLiteral<[
                                                     //   TLiteral<'prop'>,
                                                     //   TUnion<[
                                                     //      TLiteral<'A'>,
                                                     //      TLiteral<'B'>,
                                                     //      TLiteral<'C'>,
                                                     //   ]>
                                                     // ]>

const R = Type.Record(K, Type.String())              // const R: TObject<{
                                                     //   propA: TString,
                                                     //   propB: TString,
                                                     //   propC: TString,
                                                     // }>

Indexed Access Types

TypeBox supports indexed access types with the Index function. This function enables uniform access to interior property and element types without having to extract them from the underlying schema representation. Index types are supported for Object, Array, Tuple, Union and Intersect types.

const T = Type.Object({                              // type T = {
  x: Type.Number(),                                  //   x: number,
  y: Type.String(),                                  //   y: string,
  z: Type.Boolean()                                  //   z: boolean
})                                                   // }

const A = Type.Index(T, ['x'])                       // type A = T['x']
                                                     //
                                                     // ... evaluated as
                                                     //
                                                     // const A: TNumber

const B = Type.Index(T, ['x', 'y'])                  // type B = T['x' | 'y']
                                                     //
                                                     // ... evaluated as
                                                     //
                                                     // const B: TUnion<[
                                                     //   TNumber,
                                                     //   TString,
                                                     // ]>

const C = Type.Index(T, Type.KeyOf(T))               // type C = T[keyof T]
                                                     //
                                                     // ... evaluated as
                                                     // 
                                                     // const C: TUnion<[
                                                     //   TNumber,
                                                     //   TString,
                                                     //   TBoolean
                                                     // ]>

Mapped Types

TypeBox supports mapped types with the Mapped function. This function accepts two arguments, the first is a union type typically derived from KeyOf, the second is a mapping function that receives a mapping key K that can be used to index properties of a type. The following implements a mapped type that remaps each property to be T | null

const T = Type.Object({                              // type T = {
  x: Type.Number(),                                  //   x: number,
  y: Type.String(),                                  //   y: string,
  z: Type.Boolean()                                  //   z: boolean
})                                                   // }

const M = Type.Mapped(Type.KeyOf(T), K => {          // type M = { [K in keyof T]: T[K] | null }
  return Type.Union([Type.Index(T, K), Type.Null()]) //
})                                                   // ... evaluated as
                                                     // 
                                                     // const M: TObject<{
                                                     //   x: TUnion<[TNumber, TNull]>,
                                                     //   y: TUnion<[TString, TNull]>,
                                                     //   z: TUnion<[TBoolean, TNull]>
                                                     // }>

Conditional Types

TypeBox supports runtime conditional types with the Extends function. This function performs a structural assignability check against the first (left) and second (right) arguments and will return either the third (true) or fourth (false) argument based on the result. The conditional types Exclude and Extract are also supported. The following shows both TypeScript and TypeBox examples of conditional types.

// Extends
const A = Type.Extends(                              // type A = string extends number ? 1 : 2
  Type.String(),                                     //   
  Type.Number(),                                     // ... evaluated as
  Type.Literal(1),                                   //
  Type.Literal(2)                                    // const A: TLiteral<2>
)

// Extract
const B = Type.Extract(                              // type B = Extract<1 | 2 | 3, 1>
  Type.Union([                                       //
    Type.Literal(1),                                 // ... evaluated as
    Type.Literal(2),                                 //
    Type.Literal(3)                                  // const B: TLiteral<1>
  ]), 
  Type.Literal(1)
)

// Exclude
const C = Type.Exclude(                              // type C = Exclude<1 | 2 | 3, 1>
  Type.Union([                                       // 
    Type.Literal(1),                                 // ... evaluated as
    Type.Literal(2),                                 //
    Type.Literal(3)                                  // const C: TUnion<[
  ]),                                                //   TLiteral<2>,
  Type.Literal(1)                                    //   TLiteral<3>,
)                                                    // ]>

Intrinsic Types

TypeBox supports the TypeScript intrinsic string manipulation types Uppercase, Lowercase, Capitalize and Uncapitalize. These types can be used to remap Literal, Template Literal and Union of Literal types.

// TypeScript
type A = Capitalize<'hello'>                         // type A = 'Hello'

type B = Capitalize<'hello' | 'world'>               // type C = 'Hello' | 'World'

type C = Capitalize<`hello${1|2|3}`>                 // type B = 'Hello1' | 'Hello2' | 'Hello3'

// TypeBox
const A = Type.Capitalize(Type.Literal('hello'))     // const A: TLiteral<'Hello'>

const B = Type.Capitalize(Type.Union([               // const B: TUnion<[
  Type.Literal('hello'),                             //   TLiteral<'Hello'>,
  Type.Literal('world')                              //   TLiteral<'World'>
]))                                                  // ]>

const C = Type.Capitalize(                           // const C: TTemplateLiteral<[
  Type.TemplateLiteral('hello${1|2|3}')              //   TLiteral<'Hello'>,
)                                                    //   TUnion<[
                                                     //     TLiteral<'1'>,
                                                     //     TLiteral<'2'>,
                                                     //     TLiteral<'3'>
                                                     //   ]>
                                                     // ]>

Transform Types

TypeBox supports value decoding and encoding with Transform types. These types work in tandem with the Encode and Decode functions available on the Value and TypeCompiler submodules. Transform types can be used to convert Json encoded values into constructs more natural to JavaScript. The following creates a Transform type to decode numbers into Dates using the Value submodule.

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

const T = Type.Transform(Type.Number())
  .Decode(value => new Date(value))                  // decode: number to Date
  .Encode(value => value.getTime())                  // encode: Date to number

const D = Value.Decode(T, 0)                         // const D = Date(1970-01-01T00:00:00.000Z)
const E = Value.Encode(T, D)                         // const E = 0

Use the StaticEncode or StaticDecode types to infer a Transform type.

import { Static, StaticDecode, StaticEncode } from '@sinclair/typebox'

const T = Type.Transform(Type.Array(Type.Number(), { uniqueItems: true }))         
  .Decode(value => new Set(value))
  .Encode(value => [...value])

type D = StaticDecode<typeof T>                      // type D = Set<number>      
type E = StaticEncode<typeof T>                      // type E = Array<number>
type T = Static<typeof T>                            // type T = Array<number>

Rest Types

TypeBox provides the Rest type to uniformly extract variadic tuples from Intersect, Union and Tuple types. This type can be useful to remap variadic types into different forms. The following uses Rest to remap a Tuple into a Union.

const T = Type.Tuple([                               // const T: TTuple<[
  Type.String(),                                     //   TString,
  Type.Number()                                      //   TNumber
])                                                   // ]>

const R = Type.Rest(T)                               // const R: [TString, TNumber]

const U = Type.Union(R)                              // const T: TUnion<[
                                                     //   TString,
                                                     //   TNumber
                                                     // ]>

Unsafe Types

TypeBox supports user defined types with Unsafe. This type allows you to specify both schema representation and inference type. The following creates an Unsafe type with a number schema that infers as string.

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

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

The Unsafe type is often used to create schematics for extended specifications like OpenAPI.

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

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

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

const StringEnum = <T extends string[]>(values: [...T]) => Type.Unsafe<T[number]>({ 
  type: 'string', enum: values 
})
const S = StringEnum(['A', 'B', 'C'])                // const S = {
                                                     //   enum: ['A', 'B', 'C']
                                                     // }

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

TypeGuard

TypeBox can check its own types with the TypeGuard module. This module is written for type introspection and provides structural tests for every built-in TypeBox type. Functions of this module return is guards which can be used with control flow assertions to obtain schema inference for unknown values. The following guards that the value T is TString.

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

const T = { [Kind]: 'String', type: 'string' }

if(TypeGuard.IsString(T)) {

  // T is TString
}

Strict

TypeBox types contain various symbol properties that are used for reflection, composition and compilation. These properties are not strictly valid Json Schema; so in some cases it may be desirable to omit them. TypeBox provides a Strict function that will omit these properties if necessary.

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

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

Values

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

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

Create

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

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

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

Clone

Use the Clone function to deeply clone a value.

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

Check

Use the Check function to type check a value.

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

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

Convert

Use the Convert function to convert a value into its target type if a reasonable conversion is possible. This function may return an invalid value and should be checked before use. Its return type is unknown.

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

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

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

Clean

Use Clean to remove excess properties from a value. This function does not check the value and returns an unknown type. You should Check the result before use. Clean is a mutable operation. To avoid mutation, Clone the value first.

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

const X = Value.Clean(T, null)                        // const 'X = null

const Y = Value.Clean(T, { x: 1 })                    // const 'Y = { x: 1 }

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

Default

Use Default to generate missing properties on a value using default schema annotations if available. This function does not check the value and returns an unknown type. You should Check the result before use. Default is a mutable operation. To avoid mutation, Clone the value first.

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

const X = Value.Default(T, null)                        // const 'X = null - non-enumerable

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

const Z = Value.Default(T, { x: 1 })                    // const 'Z = { x: 1, y: 0 }

Cast

Use the Cast function to upcast a value into a target type. This function will retain as much infomation as possible from the original value. The Cast function is intended to be used in data migration scenarios where existing values need to be upgraded to match a modified type.

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

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

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

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

Decode

Use the Decode function to decode a value from a type or throw if the value is invalid. The return value will infer as the decoded type. This function will run Transform codecs if available.

const A = Value.Decode(Type.String(), 'hello')        // const A = 'hello'

const B = Value.Decode(Type.String(), 42)             // throw

Encode

Use the Encode function to encode a value to a type or throw if the value is invalid. The return value will infer as the encoded type. This function will run Transform codecs if available.

const A = Value.Encode(Type.String(), 'hello')        // const A = 'hello'

const B = Value.Encode(Type.String(), 42)             // throw

Equal

Use the Equal function to deeply check for value equality.

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

Hash

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

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

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

Diff

Use the Diff function to generate a sequence of edits that will transform one value into another.

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

Patch

Use the Patch function to apply a sequence of edits.

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

const B = { x: 3 }

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

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

Errors

Use the Errors function to enumerate validation errors.

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

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

Mutate

Use the Mutate function to perform a deep mutable value assignment while retaining internal references.

const Y = { z: 1 }                                   // const Y = { z: 1 }
const X = { y: Y }                                   // const X = { y: { z: 1 } }
const A = { x: X }                                   // const A = { x: { y: { z: 1 } } }

Value.Mutate(A, { x: { y: { z: 2 } } })              // A' = { x: { y: { z: 2 } } }

const R0 = A.x.y.z === 2                             // const R0 = true
const R1 = A.x.y === Y                               // const R1 = true
const R2 = A.x === X                                 // const R2 = true

Pointer

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

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

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

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

TypeRegistry

The TypeBox type system can be extended with additional types and formats using the TypeRegistry and FormatRegistry modules. These modules integrate deeply with TypeBox's internal type checking infrastructure and can be used to create application specific types, or register schematics for alternative specifications.

TypeRegistry

Use the TypeRegistry to register a type. The Kind must match the registered type name.

import { TSchema, Kind, TypeRegistry } from '@sinclair/typebox'

TypeRegistry.Set('Foo', (schema, value) => value === 'foo')

const Foo = { [Kind]: 'Foo' } as TSchema 

const A = Value.Check(Foo, 'foo')                    // const A = true

const B = Value.Check(Foo, 'bar')                    // const B = false

FormatRegistry

Use the FormatRegistry to register a string format.

import { FormatRegistry } from '@sinclair/typebox'

FormatRegistry.Set('foo', (value) => value === 'foo')

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

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

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

TypeCheck

TypeBox types target Json Schema Draft 7 and are compatible with any validator that supports this specification. TypeBox also provides a built in type checking compiler designed specifically for TypeBox types that offers high performance compilation and value checking.

The following sections detail using Ajv and the TypeBox compiler infrastructure.

Ajv

The following shows the recommended setup for Ajv.

$ npm install ajv ajv-formats --save
import { Type }   from '@sinclair/typebox'
import addFormats from 'ajv-formats'
import Ajv        from 'ajv'

const ajv = addFormats(new Ajv({}), [
  'date-time',
  'time',
  'date',
  'email',
  'hostname',
  'ipv4',
  'ipv6',
  'uri',
  'uri-reference',
  'uuid',
  'uri-template',
  'json-pointer',
  'relative-json-pointer',
  'regex'
])

const validate = ajv.compile(Type.Object({
  x: Type.Number(),
  y: Type.Number(),
  z: Type.Number()
}))

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

TypeCompiler

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

The TypeCompiler is provided as an optional import.

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

Use the Compile function to JIT compile a type. Note that compilation is generally an expensive operation and should only be performed once per type during application start up. TypeBox does not cache previously compiled types, and applications are expected to hold references to each compiled type for the lifetime of the application.

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

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

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

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

const value = { }

const first = C.Errors(value).First()                // const first = {
                                                     //   schema: { type: 'number' },
                                                     //   path: '/x',
                                                     //   value: undefined,
                                                     //   message: 'Expected number'
                                                     // }

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

Use the Code function to generate assertion functions as strings. This function can be used to generate code that can be written to disk as importable modules. This technique is sometimes referred to as Ahead of Time (AOT) compilation. The following generates code to check a string.

const C = TypeCompiler.Code(Type.String())           // const C = `return function check(value) {
                                                     //   return (
                                                     //     (typeof value === 'string')
                                                     //   )
                                                     // }`

TypeSystem

The TypeBox TypeSystem module provides configurations to use either Json Schema or TypeScript type checking semantics. Configurations made to the TypeSystem module are observed by the TypeCompiler, Value and Error modules.

Policies

TypeBox validates using standard Json Schema assertion policies by default. The TypeSystemPolicy module can override some of these to have TypeBox assert values inline with TypeScript static checks. It also provides overrides for certain checking rules related to non-serializable values (such as void) which can be helpful in Json based protocols such as Json Rpc 2.0.

The following overrides are available.

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

// Disallow undefined values for optional properties (default is false)
//
// const A: { x?: number } = { x: undefined } - disallowed when enabled

TypeSystemPolicy.ExactOptionalPropertyTypes = true

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

TypeSystemPolicy.AllowArrayObject = true

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

TypeSystemPolicy.AllowNaN = true

// Allow void types to check with undefined and null (default is false)
//
// Used to signal void return on Json-Rpc 2.0 protocol

TypeSystemPolicy.AllowNullVoid = true

Error Function

Error messages in TypeBox can be customized by defining an ErrorFunction. This function allows for the localization of error messages as well as enabling custom error messages for custom types. By default, TypeBox will generate messages using the en-US locale. To support additional locales, you can replicate the function found in src/errors/function.ts and create a locale specific translation. The function can then be set via SetErrorFunction.

The following example shows an inline error function that intercepts errors for String, Number and Boolean only. The DefaultErrorFunction is used to return a default error message.

import { SetErrorFunction, DefaultErrorFunction, ValueErrorType } from '@sinclair/typebox/errors'

SetErrorFunction((error) => { // i18n override
  switch(error.errorType) {
    /* en-US */ case ValueErrorType.String: return 'Expected string'
    /* fr-FR */ case ValueErrorType.Number: return 'Nombre attendu'  
    /* ko-KR */ case ValueErrorType.Boolean: return '예상 부울'      
    /* en-US */ default: return DefaultErrorFunction(error)          
  }
})
const T = Type.Object({                              // const T: TObject<{
  x: Type.String(),                                  //  TString,
  y: Type.Number(),                                  //  TNumber,
  z: Type.Boolean()                                  //  TBoolean
})                                                   // }>

const E = [...Value.Errors(T, {                      // const E = [{
  x: null,                                           //   type: 48,
  y: null,                                           //   schema: { ... },
  z: null                                            //   path: '/x',
})]                                                  //   value: null,
                                                     //   message: 'Expected string'
                                                     // }, {
                                                     //   type: 34,
                                                     //   schema: { ... },
                                                     //   path: '/y',
                                                     //   value: null,
                                                     //   message: 'Nombre attendu'
                                                     // }, {
                                                     //   type: 14,
                                                     //   schema: { ... },
                                                     //   path: '/z',
                                                     //   value: null,
                                                     //   message: '예상 부울'
                                                     // }]

TypeBox Workbench

TypeBox offers a web based code generation tool that can convert TypeScript types into TypeBox types as well as several other ecosystem libraries.

TypeBox Workbench Link Here

TypeBox Codegen

TypeBox provides a code generation library that can be integrated into toolchains to automate type translation between TypeScript and TypeBox. This library also includes functionality to transform TypeScript types to other ecosystem libraries.

TypeBox Codegen Link Here

Ecosystem

The following is a list of community packages that offer general tooling, extended functionality and framework integration support for TypeBox.

Package Description
drizzle-typebox Generates TypeBox types from Drizzle ORM schemas
elysia Fast and friendly Bun web framework
fastify-type-provider-typebox Fastify TypeBox integration with the Fastify Type Provider
feathersjs The API and real-time application framework
fetch-typebox Drop-in replacement for fetch that brings easy integration with TypeBox
h3-typebox Schema validation utilities for h3 using TypeBox & Ajv
http-wizard Type safe http client library for Fastify
openapi-box Generate TypeBox types from OpenApi IDL + Http client library
prismabox Converts a prisma.schema to typebox schema matching the database models
schema2typebox Creating TypeBox code from Json Schemas
sveltekit-superforms A comprehensive SvelteKit form library for server and client validation
ts2typebox Creating TypeBox code from Typescript types
typebox-form-parser Parses form and query data based on TypeBox schemas
typebox-validators Advanced validators supporting discriminated and heterogeneous unions

Benchmark

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

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

Compile

This benchmark measures compilation performance for varying types.

┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┐
          (index)            Iterations      Ajv       TypeCompiler  Performance  
├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┤
 Literal_String                 1000     '    242 ms'  '     10 ms'  '   24.20 x' 
 Literal_Number                 1000     '    200 ms'  '      8 ms'  '   25.00 x' 
 Literal_Boolean                1000     '    168 ms'  '      6 ms'  '   28.00 x' 
 Primitive_Number               1000     '    165 ms'  '      8 ms'  '   20.63 x' 
 Primitive_String               1000     '    154 ms'  '      6 ms'  '   25.67 x' 
 Primitive_String_Pattern       1000     '    208 ms'  '     14 ms'  '   14.86 x' 
 Primitive_Boolean              1000     '    142 ms'  '      6 ms'  '   23.67 x' 
 Primitive_Null                 1000     '    143 ms'  '      6 ms'  '   23.83 x' 
 Object_Unconstrained           1000     '   1217 ms'  '     31 ms'  '   39.26 x' 
 Object_Constrained             1000     '   1275 ms'  '     26 ms'  '   49.04 x' 
 Object_Vector3                 1000     '    405 ms'  '     12 ms'  '   33.75 x' 
 Object_Box3D                   1000     '   1833 ms'  '     27 ms'  '   67.89 x' 
 Tuple_Primitive                1000     '    475 ms'  '     13 ms'  '   36.54 x' 
 Tuple_Object                   1000     '   1267 ms'  '     30 ms'  '   42.23 x' 
 Composite_Intersect            1000     '    604 ms'  '     18 ms'  '   33.56 x' 
 Composite_Union                1000     '    545 ms'  '     20 ms'  '   27.25 x' 
 Math_Vector4                   1000     '    829 ms'  '     12 ms'  '   69.08 x' 
 Math_Matrix4                   1000     '    405 ms'  '     10 ms'  '   40.50 x' 
 Array_Primitive_Number         1000     '    372 ms'  '     12 ms'  '   31.00 x' 
 Array_Primitive_String         1000     '    327 ms'  '      5 ms'  '   65.40 x' 
 Array_Primitive_Boolean        1000     '    300 ms'  '      4 ms'  '   75.00 x' 
 Array_Object_Unconstrained     1000     '   1755 ms'  '     21 ms'  '   83.57 x' 
 Array_Object_Constrained       1000     '   1516 ms'  '     20 ms'  '   75.80 x' 
 Array_Tuple_Primitive          1000     '    825 ms'  '     14 ms'  '   58.93 x' 
 Array_Tuple_Object             1000     '   1616 ms'  '     16 ms'  '  101.00 x' 
 Array_Composite_Intersect      1000     '    776 ms'  '     16 ms'  '   48.50 x' 
 Array_Composite_Union          1000     '    820 ms'  '     14 ms'  '   58.57 x' 
 Array_Math_Vector4             1000     '   1166 ms'  '     15 ms'  '   77.73 x' 
 Array_Math_Matrix4             1000     '    695 ms'  '      8 ms'  '   86.88 x' 
└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┘

Validate

This benchmark measures validation performance for varying types.

┌────────────────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐
          (index)            Iterations   ValueCheck       Ajv       TypeCompiler  Performance  
├────────────────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤
 Literal_String               1000000    '     18 ms'  '      5 ms'  '      4 ms'  '    1.25 x' 
 Literal_Number               1000000    '     16 ms'  '     18 ms'  '     10 ms'  '    1.80 x' 
 Literal_Boolean              1000000    '     15 ms'  '     19 ms'  '     10 ms'  '    1.90 x' 
 Primitive_Number             1000000    '     21 ms'  '     19 ms'  '     10 ms'  '    1.90 x' 
 Primitive_String             1000000    '     22 ms'  '     18 ms'  '      9 ms'  '    2.00 x' 
 Primitive_String_Pattern     1000000    '    155 ms'  '     41 ms'  '     34 ms'  '    1.21 x' 
 Primitive_Boolean            1000000    '     18 ms'  '     17 ms'  '      9 ms'  '    1.89 x' 
 Primitive_Null               1000000    '     19 ms'  '     17 ms'  '      9 ms'  '    1.89 x' 
 Object_Unconstrained         1000000    '   1003 ms'  '     32 ms'  '     24 ms'  '    1.33 x' 
 Object_Constrained           1000000    '   1265 ms'  '     49 ms'  '     38 ms'  '    1.29 x' 
 Object_Vector3               1000000    '    418 ms'  '     22 ms'  '     13 ms'  '    1.69 x' 
 Object_Box3D                 1000000    '   2035 ms'  '     56 ms'  '     49 ms'  '    1.14 x' 
 Object_Recursive             1000000    '   5243 ms'  '    326 ms'  '    157 ms'  '    2.08 x' 
 Tuple_Primitive              1000000    '    153 ms'  '     20 ms'  '     12 ms'  '    1.67 x' 
 Tuple_Object                 1000000    '    781 ms'  '     28 ms'  '     18 ms'  '    1.56 x' 
 Composite_Intersect          1000000    '    742 ms'  '     25 ms'  '     14 ms'  '    1.79 x' 
 Composite_Union              1000000    '    558 ms'  '     24 ms'  '     13 ms'  '    1.85 x' 
 Math_Vector4                 1000000    '    246 ms'  '     22 ms'  '     11 ms'  '    2.00 x' 
 Math_Matrix4                 1000000    '   1052 ms'  '     43 ms'  '     28 ms'  '    1.54 x' 
 Array_Primitive_Number       1000000    '    272 ms'  '     22 ms'  '     12 ms'  '    1.83 x' 
 Array_Primitive_String       1000000    '    235 ms'  '     24 ms'  '     14 ms'  '    1.71 x' 
 Array_Primitive_Boolean      1000000    '    134 ms'  '     23 ms'  '     14 ms'  '    1.64 x' 
 Array_Object_Unconstrained   1000000    '   6280 ms'  '     65 ms'  '     59 ms'  '    1.10 x' 
 Array_Object_Constrained     1000000    '   6076 ms'  '    130 ms'  '    119 ms'  '    1.09 x' 
 Array_Object_Recursive       1000000    '  22738 ms'  '   1730 ms'  '    635 ms'  '    2.72 x' 
 Array_Tuple_Primitive        1000000    '    689 ms'  '     35 ms'  '     30 ms'  '    1.17 x' 
 Array_Tuple_Object           1000000    '   3266 ms'  '     63 ms'  '     52 ms'  '    1.21 x' 
 Array_Composite_Intersect    1000000    '   3310 ms'  '     44 ms'  '     36 ms'  '    1.22 x' 
 Array_Composite_Union        1000000    '   2432 ms'  '     69 ms'  '     33 ms'  '    2.09 x' 
 Array_Math_Vector4           1000000    '   1158 ms'  '     37 ms'  '     24 ms'  '    1.54 x' 
 Array_Math_Matrix4           1000000    '   5435 ms'  '    132 ms'  '     92 ms'  '    1.43 x' 
└────────────────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘

Compression

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

┌──────────────────────┬────────────┬────────────┬─────────────┐
       (index)          Compiled    Minified   Compression 
├──────────────────────┼────────────┼────────────┼─────────────┤
 typebox/compiler      '126.9 kb'  ' 55.7 kb'   '2.28 x'   
 typebox/errors        ' 46.1 kb'  ' 20.8 kb'   '2.22 x'   
 typebox/system        '  4.7 kb'  '  2.0 kb'   '2.33 x'   
 typebox/value         '152.2 kb'  ' 64.5 kb'   '2.36 x'   
 typebox               ' 95.7 kb'  ' 39.8 kb'   '2.40 x'   
└──────────────────────┴────────────┴────────────┴─────────────┘

Contribute

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

typebox's People

Contributors

alexbadm avatar castarco avatar ciscoheat avatar dwickern avatar erfanium avatar flodlc avatar fox1t avatar geekflyer avatar ghalle avatar gorbak25 avatar hamishwhc avatar jayalfredprufrock avatar jhewlett avatar joshmossas avatar khanguslee avatar lsg-radu avatar m-ronchi avatar matomesc avatar matteovivona avatar mooyoul avatar noamokman avatar rubiagatra avatar sds avatar sinclairzx81 avatar smitssjors avatar stevezhu avatar sunaurus avatar tinchoz49 avatar voda avatar xddq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typebox's Issues

A `TObject` With No/Optional-only Properties Has Invalid Static Type

I've come across an issue which I believe to be a bug in TypeBox (version 0.16.5) where a variable declared as a TObject, containing either all optional properties or no properties at all, becomes a top type that is assignable to anything except for undefined|null. I've provided a simple example below to demonstrate the issue. Is this type of behavior intended?

import { Static, Type } from "@sinclair/typebox";

let Test = Type.Object({
    key: Type.Optional(Type.Number()) // 
});

type TestType = Static<typeof Test>;

// Passes, but I don't believe it should...
let test: TestType = "this works";

Recursive type support

I have some types which define recursive logical operations:

type Operator = 'and' | 'or';
type Operand = {
  name: 'operandA' | 'operandB' | 'operandC';
};
export type Condition = {
  operator: Operator;
  operands: Array<Condition | Operand>;
};

Which allows me to define a condition like this:

const condition: Condition = {
  operator: 'and',
  operands: [
    {
      name: 'operandA',
    },
    {
      operator: 'or',
      operands: [
        {
          name: 'operandB',
        },
        {
          name: 'operandC',
        },
      ],
    },
  ],
};

Which is equivalent to operandA and (operandB or operandC)

Is this representation currently possible with typebox?

Is it possible to merge/modify typeboxes?

Hi

Is it possible to merge or somehow modify typebox?

For example:

const ModelInput = Type.Object({
  name: Type.String(),
});

const Model = Type.Object({
  id: Type.string(),
  ...ModelInput
})

Or vice-versa use some utility like pick/omit to modify it?

Thanks in advance

Type is not correctly inferred

This may be more of a question than an issue, but for some reason the type does not seem to be correctly inferred when I try this library:

const querySchema = Type.Object({
  page: Type.Integer({ default: 0, minimum: 0 }),
  page_size: Type.Integer({ default: 25, minimum: 1 }),
});

type TQuery = Static<typeof querySchema>;

image

image

In my example TQuery is pretty much useless :/
What am I doing wrong?
(tried with TS 3.9.7 and 4.0.2, in VSCode)

null passes validation

Hi! Passing null to fields Type.String(), Type.Integer() or Type.Number() passes ajv validation on fastify.

Not sure how to fix it.

export const TBody = Type.Object({
    phoneNumber: Type.String(),
    timestampt: Type.Integer()
});

body: TBody
and POST request with

{
    phoneNumber: null,
    timestamp: null
}

[Feature Request] Add support for creating oneOf schema

Currently, I we can create anyOf and allOf schema with Union and Intersect. However, we are missing the oneOf schema.

Note. OneOf typing should be the same as anyOf.
For example:

const T = Type.Either([
  Type.String(),
  Type.Number()
])

type T = string | number

const T = {
  oneOf: [
    { type: 'string' },
    { type: 'number" }
  ]
}

custom string formats?

Hey sinclairzx81,
Thanks for the awesome package. I'm having an issue adding custom string formats. The CustomOptions interface seems to indicate that you had in mind some way to do this, probably using delicious generics, but I was unable to sort it out. I've been basically hacking it with module augmentation:

import { CustomOptions } from '@sinclair/typebox';

declare module '@sinclair/typebox' {
  interface CustomOptions {
    format?: 'mongoId' | 'jwt';
  }
}

But this is bad. I've been trying to figure out the intended way to use Custom Options, but now I'm hungry and tired. Can you just tell me the answer? Thanks :)

Override TS types?

Is there a way to override what TS type is generated for a given type?

I'm using type-fest's Opaque type to distinguish between different "kinds" of primitives (e.g. strings that represent URLs). There doesn't currently seem to be a way to represent these in a typebox schema.

A possible API could look like this:

// from type-fest
type UrlString = Opaque<string, "url">;

// schema
const File = Type.Object({
  url: Type.Opaque<UrlString>(Type.String()),
  title: Type.String()
});
type File = Static<typeof File>; // { url: Opaque<string, "url">, title: string }

This wouldn't have to be tied to type-fest specifically. Type.Opaque could serve as a general escape-hatch to override the "natural" type. Maybe it could be renamed to avoid confusion.

How to have an Object+Dict?

Hello, basically the desire here is to get the below type:

type Metadata = {
	provider: "gcs" | "s3"
	bucket: string
	name: string
	[key: string]: any
}

I've tried to do:

const Metadata = Type.Intersect(
	[
		Type.Dict(Type.Any()),
		Type.Object({
			provider: Type.Union([Type.Literal(`gcs`), Type.Literal(`s3`)]),
			bucket: Type.String({ minLength: 1 }),
			name: Type.String({ minLength: 1 }),
		})
	]
)

But it gives me an error on Type.Dict(Type.Any()),:

Type 'TDict<TAny>' is not assignable to type 'TObject<TProperties>'.
  Property 'properties' is missing in type 'TDict<TAny>' but required in type '{ kind: unique symbol; type: "object"; additionalProperties: false; properties: TProperties; required?: string[] | undefined; }'.ts(2322)
typebox.d.ts(78, 5): 'properties' is declared here.

Let me know if I have missed something!

Thank you!

Type.Union() should result in anyOf instead of oneOf

This code:

const FirstSchema = Type.Object({foo: Type.String()})
const SecondSchema = Type.Object({foo: Type.String(), bar: Type.Optional(Type.String())})
const Union = Type.Union([FirstSchema, SecondSchema]);

Generates the following schema:

    {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "foo": {
              "type": "string"
            }
          },
          "required": [
            "foo"
          ]
        },
        {
          "type": "object",
          "properties": {
            "foo": {
              "type": "string"
            },
            "bar": {
              "type": "string"
            }
          },
          "required": [
            "foo"
          ]
        }
      ]
    }

The issue is that it uses oneOf instead of anyOf - oneOf means that objects may match exactly one schema, but in TypeScript, unions work like anyOf, not oneOf. With anyOf, objects must match at least one schema.

For example, this is valid TypeScript:

type FirstType = {
  foo: string;
}

type SecondType = {
  foo: string;
  bar?: string;
}

type UnionType = FirstType | SecondType;

const test: UnionType = {foo: "test"};

However, {foo: "test"} will not match the Union schema shown above, because:

JSON is valid against more than one schema from 'oneOf'.

Would you accept a PR that changes oneOf to anyOf for Type.Union()?

Disallow additional properties?

Hello, do you have any idea as to how I would disallow additional properties when validating?
I've read through ajv and found additionalProperties: false.

function TObject<T extends TProperties>(props: T, options?: CustomOptions) {
  return Type.Object<T>(props, { ...options, additionalProperties: false });
}

I've built my schema up to look like this:
const AttrObject = Type.Dict(AttributeValue);
Where AttributeValue is built up to look like this:
billede
Ignore the "value" key.

Validating against this should work, but I still get errors?

{
   "field1": { "type": "string"  }
}

Here's the raw json of the schema: https://pastebin.com/E1xwx1C5
And here are the errors I get: https://pastebin.com/iEYsekBH

Usage with latest ajv leads to "unknown keyword kind"

ajv has released a new strict mode https://github.com/ajv-validator/ajv/blob/master/docs/strict-mode.md#strict-mode, and the example in the readme doesn't work. One should turn off the strict mode:

  const validate = new Ajv({ strict: "log" }).compile(PostSchema);

  const postData = {
    title: data.title,
    createdAt: data.createdAt,
    slug: data.slug,
    tags: data.tags,
    description: data.description,
    path: `/posts/${data.slug}`,
  };

  const isValid = validate(postData);
  if (!isValid) {
    console.error(validate.errors);
    throw new Error(`Invalid data found for post`);
  }

Error: A rest element type must be an array type.

I have an issue with the lastest version 0.11.0:

node_modules/@sinclair/typebox/typebox.d.ts:6:17 - error TS2574: A rest element type must be an array type.

6     arguments: [...T];
                  ~~~~

node_modules/@sinclair/typebox/typebox.d.ts:11:17 - error TS2574: A rest element type must be an array type.

11     arguments: [...T];
                   ~~~~

and so on...

If I downgrade to 0.10.1, the error is not here.

Typescript version: 4.0.5

Utility Types: Partial, Required, Omit, Pick

It might be interesting to implement a subset of TypeScript's Utility Types. I expect this functionality would only apply to schemas of type TObject<Properties> and have the following behavior.

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

const PartialVector3 = Type.Partial(Vector3)         // { x?: number, y?: number, z?: number }

const RequiredVector3 = Type.Required(PartialVector3) // { x: number, y: number, z: number }

const Vector2 = Type.Pick(Vector3, ['x', 'y'])       // { x: number, y: number }

const Vector2 = Type.Omit(Vector3, ['z'])            // { x: number, y: number }

Having the ability to partial on a Type may help applications that use partial objects to update records in CRUD scenarios. Not having the ability to Partial<T> on a common type would lead to duplication of that type (one for Required and one for Partial). For consideration.

Got error TS2315 with recently released TS 3.9

Hi,

I was using your great package on TS 3.8
I've just installed TS 3.9; since, the compiler complains about (mainly, but not only) this error:

error TS2315: Type 'Static' is not generic.

It might be due to this BC but i'm not sure: Type Parameters That Extend any No Longer Act as any

Right now I will stay on TS 3.8.

I don't know how I can help you more on this issue (except submitting a PR, but I don't know how to fix the issue right now)

Thanks,
Regards.

Causing issues with latest Ajv

The new version of Ajv (v7) enables strict mode by default. This seems to break validation using typebox with these errors:

Error: strict mode: unknown keyword: "kind"
4128
      at Object.checkStrictMode (/root/node_modules/ajv/lib/compile/validate/index.ts:197:28)
4129
      at Object.checkUnknownRules (/root/node_modules/ajv/lib/compile/util.ts:27:22)
4130
      at checkKeywords (/root/node_modules/ajv/lib/compile/validate/index.ts:129:3)
4131
      at Object.validateFunctionCode (/root/node_modules/ajv/lib/compile/validate/index.ts:15:5)
4132
      at Ajv.compileSchema (/root/node_modules/ajv/lib/compile/index.ts:151:5)
4133
      at Ajv._compileSchemaEnv (/root/node_modules/ajv/lib/core.ts:659:24)
4134
      at Ajv.compile (/root/node_modules/ajv/lib/core.ts:323:34)

Is there some keyword being added to the schema for certain types under the hood?

Union of unions

Hi, it it possible to create a union of unions?

I tried doing the following

Type.Union([
  Type.Union([ ... ]),
  Type.Union([ ... ])
]);

but the static type is any.

My use case is a large union that I would like to break up into smaller unions. I suppose that increase the union size from 8 can also work but I'd rather compose the smaller unions.

CI/CD support

Hi @sinclairzx81 we at HospitalRun decided to base our data and db validation structure upon this library.

Would you mind if we make a PR to typebox to add GitHub actions for building and testing it automatically?

In addition to that, if you like also other automation as Coveralls or auto publish on npm just ping us.

[Feature Proposal] Add extend function

Motivation

Working on complex schema can be tedious because of many common part repetitions.

Idea

It would be helpful to have something similar to this:

function extend<F, S>(firstSchema: F, secondSchema: S): F & S {
  if (firstSchema.type !== 'object' || secondSchema.type !== 'object') {
    throw new Error(`Only object schemas can be extended.`)
  }
  return {
    type: 'object',
    properties: {
      ...firstSchema.properties,
      ...secondSchema.properties,
    },
    required: (firstSchema.required || []).concat(secondSchema.required),
  }
}

Another example of this approach can be find here: https://github.com/fastify/fluent-schema/blob/master/src/ObjectSchema.js#L250

Example

export const channelSchema = Type.Object({
  channel: Type.String(),
  qapla: Type.Optional(
    Type.Object({
      apikey: Type.String(),
      callOn: Type.Union([Type.Literal('PACKING'), Type.Literal('SHIPPING')]),
      reference: Type.Union([Type.Literal('rifOrder'), Type.Literal('orderNumber')]),
    }),
  ),
})

const savedDocument = Type.Object({
  _id: ObjectId,
  tenantId: ObjectId,
  createdAt: Type.String({ format: 'date-time' }),
  modifiedAt: Type.String({ format: 'date-time' }),
  createdBy: ObjectId,
  modifiedBy: Type.Optional(ObjectId),
})

export const responseSchema = extend(savedDocument, channelSchema)

how to default Type.Number to null

example
jobTitleId: Type.Optional(Type.Number())

when request body is
{
"industryGroupId": null
}
how can i defualt jobTitleId to null now it is 0

Error TS2315 with TSDX

I'm using TSDX with defaults settings and getting a TS2315


export const phoneInputValue = Type.Object({
  countryCode: Type.String(),
  isoCode: Type.String(),
  phone: Type.String(),
});

export type PhoneInputValueType = Static<typeof phoneInputValue>;

The error is :

@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`.
@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`.
✓ Creating entry file 1 secs
(typescript) Error: /home/edy/projectos/temp/prueba/src/index.ts(9,35): semantic error TS2315: Type 'Static' is not generic.
Error: /home/edy/projectos/temp/prueba/src/index.ts(9,35): semantic error TS2315: Type 'Static' is not generic.
    at error (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:5400:30)
    at throwPluginError (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:11878:12)
    at Object.error (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:12912:24)
    at Object.error (/home/edy/projectos/temp/prueba/node_modules/rollup/dist/shared/node-entry.js:12081:38)
    at RollupContext.error (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:17237:30)
    at /home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:25033:23
    at arrayEach (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:545:11)
    at Function.forEach (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:9397:14)
    at printDiagnostics (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:25006:12)
    at Object.transform (/home/edy/projectos/temp/prueba/node_modules/tsdx/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:29277:17)

Even with the plugin replace warming fixed the error apear.

TTuple is not exported

I've run into this problem when using Type.Tuple() with this minimal example:

import { Type } from '@sinclair/typebox';

export const schema = Type.Tuple({});

The normal solution is providing a type definition to schema, but the main reason I'm using typebox is because types can be inferred.

Another solution would be exporting TTuple1 ... TTuple8 in typebox.d.ts.

lose types when exporting

Hi,
there is an issue when export the types (may be with Type.Union)

consider the following
module-a

import { Type, Static } from "@sinclair/typebox";

export const roleSchema = Type.Union([
  Type.Literal("ADMIN"),
  Type.Literal("MEMBER"),
]);
export const permissionSchema = Type.Union([
  Type.Literal("SUPERADMIN"),
  Type.Literal("CONTROLPANEL_ACCESS"),
]);
export const userSchema = Type.Object({
  uid: Type.String(),
  email: Type.String(),
  role: roleSchema,
  permissions: Type.Array(permissionSchema),
});

export type User = Static<typeof userSchema>

Inside module-a everything work fine, in fact

type User = {} & {} & {} & {
    uid: string;
    email: string;
    role: "ADMIN" | "MEMBER";
    permissions: StaticArray<TUnion<[TLiteral<"SUPERADMIN">, TLiteral<"CONTROLPANEL_ACCESS">]>>;
}

The issue is when we import the types into another module

module-b

import { User } from "module-a"
// we lose types
type User = {} & {} & {} & {
    uid: string;
    email: string;
    role: any;
    permissions: StaticArray<TUnion<TSchema[]>>;
}

optional properties?

Hi! It is possible to define an optional object property?

What I mean is something that, in Typescript, would be defined like b below:

type MyType = {
   a: string,
   b?: string 
}

In this case, a must be there but b may be absent.

We at first thought this could be defined with something like this, with typebox:

const MyTypeSchema = Type.Object({
   a: Type.String(),
   b: Type.Optional(Type.String())
})

But that's not quite the same. It leads to a type like this:

type MyType = {
   a: string,
   b: string  // <--- we'd want `b?: string`
}

Just wondering if we're missing something with respect to optional properties, or if the project does not allow them?

Thank you!
Dan

Union with Type.Undefined() produces any

Using Type.Undefined() in union always yields any

Screen Shot 2020-08-18 at 4 44 32 PM

I would expect mediaUrl to be a union of string | null | undefined, however I see any

TSC version: 3.8.3
Also thanks a lot for working on this project :)

Unknown type

Hi,

first thank you for this great tool!

Do you think it is possible do add the unknown type?

Type.Any() is not working with Fastify response schmea

example

export const responseSchema = Type.Object({
  code: Type.Number(),
  subcode: Type.Number(),
  message: Type.String(),
  data: Type.Dict(Type.Any()) ,
})

Getting a error when reply send

const Controller: FastifyPluginCallback = (server, options, next) => {
  server.post(
    '/:moduleName/:action',
    {
      schema: {
        body: bodySchema,
        params: paramsSchema,
        response: {
          '2xx': responseSchema,
        },
      },
    },
    async (request, reply) => {
      reply.send({
        code: 0,
        subcode: 0,
        message: 'ok',
        data: {
          a: '123',
        },
      })
    }
  )
  next()
}
Error: Cannot coerce 123 to undefined

[email protected]
@sinclair/[email protected]

LiteralKind is not defined when using fast-json-stringify

Type.Literal with Type.Union causes a ReferenceError error when using fast-json-stringify.

Type.Object({
  option: Type.Union([Type.Literal('pizza'), Type.Literal('salad'), Type.Literal('pie')]),
});
ReferenceError: LiteralKind is not defined
	at Object.$main (eval at build (/usr/src/app/.yarn/cache/fast-json-stringify-npm-2.2.9-c510e40cf5-f481a8e3e1.zip/node_modules/fast-json-stringify/index.js:158:20), <anonymous>:181:44)
	at serialize (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/validation.js:116:41)
	at preserializeHookEnd (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/reply.js:348:15)
	at next (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:198:7)
	at Object.<anonymous> (/usr/src/app/packages/tsi-core/src/plugins/replyCommonHeadersPlugin.ts:30:20)
	at next (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:202:34)
	at Object.<anonymous> (/usr/src/app/packages/tsi-core/src/plugins/replyResourcePlugin.ts:30:9)
	at next (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:202:34)
	at onSendHookRunner (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/hooks.js:216:3)
	at preserializeHook (/usr/src/app/.yarn/cache/fastify-npm-3.7.0-a75b1a843e-1a1d0d55eb.zip/node_modules/fastify/lib/reply.js:327:5)

Typebox version: 0.12.4

New version stopped working with Fastify schema validation

We are using Typebox for our Fastify schema validation. Example:

server.post<{ Body: NodeParams.RequestSetup }>(
  "/setup",
  { schema: { body: Type.Intersect([...]), response: {
    200: Type.Object({
      ...
    }), 
  } },
  async (request, reply) => {
    ...
  },
);

Getting this error on requests now:

node:258) UnhandledPromiseRejectionWarning: Error: schema is invalid: data.allOf[0].properties['meta'].properties['kind'] should be object,boolean
    at Ajv.validateSchema (/root/node_modules/ajv/lib/ajv.js:178:16)
    at Ajv._addSchema (/root/node_modules/ajv/lib/ajv.js:307:10)
    at Ajv.compile (/root/node_modules/ajv/lib/ajv.js:113:24)

Any idea what is going on?

'modifierSymbol' breaks type inferrance

When upgrading typebox from 0.9 to 0.10 I get the following error when using Type.Optional:

Exported variable has or is using name 'modifierSymbol' from external module ".../node_modules/@sinclair/typebox/typebox" but cannot be named, e.g. when defining

export const optionalStringType = Type.Optional(Type.String());

Usually the suggested fix is to define the type, but the whole reason I use typebox is that it can infer types.

codegen from JSON Schema?

Wondering if there are any plans for this, and if not, would this be an interesting addition?

E.g. given a JSON Schema -> generate typebox definitions.

A way to merge with existing types

Firstly, I'm sorry if this is a newbie question. I'm a relatively new convert to typescript and still figuring my way around.

I'm currently using genql to generate a typescript lib from my GraphQL server. I'd like to import that definition into a typebox object (if this is even possible). Here's an example:

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

export type TBody = Static<typeof body>
const body = Type.Object({
  message: Type.String(),
  full_name: Type.String(),
  preferred_name: Type.String(),
  email: Type.String(),
  phone: Type.String(),
  password: Type.String(),
  currency: currencies_enum,
})

Where currencies_enum looks like this:

export type currencies_enum = 'AED' | 'AUD' | 'BRL' | 'CAD' | 'CHF' | 'CLP' | 'CNY' | 'CZK' | 'EUR' | 'GBP' | 'HKD' | 'IDR' | 'INR' | 'JPY' | 'KZT' | 'MOP' | 'MXN' | 'MYR' | 'NAD' | 'NGN' | 'NOK' | 'NZD' | 'PHP' | 'PKR' | 'PLN' | 'QAR' | 'RON' | 'RUB' | 'SAR' | 'SEK' | 'SGD' | 'THB' | 'TOP' | 'TRY' | 'TWD' | 'UAH' | 'USD' | 'VND' | 'VUV' | 'XAF' | 'ZAR'

Is there a function I can use to merge that currencies_enum type into the typebox representation? My primary reason for this is such that I can spit out a consistent typescript and json schema representation of the same type.

Thanks in advance. Any insight here would be a learning experience for me. 🙇🏻‍♂️

Intersection of an Object and Union

I was wondering if it was possible to do an intersection of an object and union.

interface BasicProps {
  id: string
  type: 'A' | 'B'
}
type Person = BasicProps & (
  {
    type: 'A'
    wallet: number
  } | {
    type: 'B'
    hat: string
  }
)

When I try doing a union inside of an intersect...

const Person = Type.Intersect([
    Type.Object({
        id: str(),
        type: Type.Union([Type.Literal('A'), Type.Literal('B')]),
    }),
    Type.Union([
        Type.Object({
            type: Type.Literal('A'),
            wallet: Type.Number(),
        }),
        Type.Object({
            type: Type.Literal('B'),
            hat: Type.String(),
        })
    ])
])

I get the error

Type 'TUnion<[TObject<{ type: TLiteral<"A">; wallet: TNumber; }>, TObject<{ type: TLiteral<"B">; hat: TString; }>]>' is not assignable to type 'TObject<TProperties>'.
  Type 'TUnion<[TObject<{ type: TLiteral<"A">; wallet: TNumber; }>, TObject<{ type: TLiteral<"B">; hat: TString; }>]>' is missing the following properties from type '{ kind: unique symbol; type: "object"; additionalProperties: false; properties: TProperties; required?: string[]; }': type, additionalProperties, properties

Is this possible to do with Typebox?

Type.Object should turn additionalProperties to off by default

I think in most cases you would NOT want additionalProperties to be true (or omitted). I don't believe that there are many use cases that require additionalProperties to be true. In case you need it, you could still pass { additionalProperties: false } in the options. Since the conversion from Types to JSONSchema is not well-defined it may make sense to allow the user to configure these kinds of details themselves using a global config object.

Typebox JSONSchema definition / self-hosting

Apologies if this is more of a suggestion/question than an issue - but doubt it would get answered anywhere else.

I have a data type that would ideally contain a dynamic JSON schema definition - the only approaches I can see how to model this currently would be to either create a Typebox definition for a valid JSON Schema (which is hopefully possible, albeit a bit of work), create a sub-format that can be compiled into a JSON Schema, or just to use the Any type and lose strict typing...

The question I guess is whether JSON Schema would make sense as a base Typebox type to allow for handling of dynamic schemas, and if that is a project worth embarking on - or if the complexity would be too high to be considered feasible.

NullKind is not defined

For version 0.12.7

Having a schema that includes Null(), e.g.

const schema = Type.Union([
  Type.Null(), 
  Type.string()
])

And calling my api that contains this schema, I get the error:
NullKind is not defined

Downgrading to 0.10.1 resolves the problem.

Unable to set { additionalProperties: true } on Type.Object().

Hello! I recently bumped my version of typebox from 0.12.0 to latest, and since then I've lost the ability to set additionalProperties to true on an object type.

I've narrowed down the change in behavior from 0.14.1 -> 0.15.0.
Suspected commit: 2657b02

Here's is a minimal reproducible example:

const response = Type.Object({
payload: Type.Object({}, {additionalProperties: true})
})

console.log(JSON.stringify(response, null, 2))

Version 0.14.1
{ "type": "object", "properties": { "payload": { "additionalProperties": true, "type": "object", "properties": {} } }, "required": [ "payload" ] }

Version 0.15.0
{ "type": "object", "additionalProperties": false, "properties": { "payload": { "additionalProperties": false, "type": "object", "properties": {} } }, "required": [ "payload" ] }

The nullable option is not reflected in TypeScript types

const NullableSchema = Type.Number({nullable: true})
type NullableSchemaType = Static<typeof NullableSchema>;
const test: NullableSchemaType = null;

results in:

error TS2322: Type 'null' is not assignable to type 'number'.

Is it even possible to fix this?

I realize that the recommended workaround is to use Type.Union() with Type.Null(), but this does not play well with some other libraries (among other reasons due to #37) and is actually considered an anti-pattern by some people: ajv-validator/ajv#1107 (comment)

[Improvement] Usage of CHANGELOG

Hey 👋,

Thank you for this awesome npm package! 😄
To ease the update of the dependency and clarify what changed between release, there should be a CHANGELOG.md file OR usage of GitHub releases with notable changes as description, this could be auto-generated, with strong commit convention.

See: https://keepachangelog.com/

Make use of $ref in JSON Schema

const Person = Type.Object({
  'name': Type.String(),
  'age': Type.Number()
});
const ChessMatch = Type.Object({
  'playerWhite': Person,
  'playerBlack': Person
});
console.log(JSON.stringify(ChessMatch));

outputs

{
  "type": "object",
  "properties": {
    "playerWhite": {
      "type": "object",
      "properties": {
        "name": {"type": "string"},
        "age": {"type": "number"}
      },
      "required": ["name","age"]
    },
    "playerBlack": {
      "type": "object",
      "properties": // same as above
// ...

This means, the definition of Person is repeated in the output. Instead, please consider using the $ref keyword. The output would then look something like this:

{
  "type": "object",
  "definitions": {
    "person": {
      "type": "object",
      "properties": {
        "name": {"type": "string"},
        "age": {"type": "number"}
      }
    }
  },
  "properties": {
    "playerWhite": {"$ref": "#/definitions/person"},
    "playerBlack": {"$ref": "#/definitions/person"}
  }
}

make modifier property non-enumerable

heyho,

we're using typebox to generate json-schemas and some of them we pass to openapi generator. Some json-schema tools, like openapi generator don't like the fact that the typebox schemas contain the modifier property which isn't actually part of the json-schema spec.
So we wrote some "post-processing" step to remove these modifier properties before passing them to openapi, which "kinda" works but is a bit ugly.

Looking at typebox' code I understand why you need these properties, however I was wondering if you could make these non-enumerable or use a symbol as property name instead? Symbols aren't enumerable via normal means and also get dropped when JSON.stringify()-ing the schema.
This mean that systems like openapi generator wouldn't actually "see" these non-spec compliant properties.

Is that something that typebox could move to?

Error when Intersect objects with same key

Step to reproduce

const A = Type.Object({
      a: Type.String(),
})
const B = Type.Object({
      a: Type.String()
})
const T = Type.Intersect([A, B])

output

Error: schema is invalid: data/required should NOT have duplicate items (items ## 1 and 0 are identical)

generated schema

{
  type: 'object',
  kind: Symbol(ObjectKind),
  additionalProperties: false,
  properties: { a: { kind: Symbol(StringKind), type: 'string' } },
  required: [ 'a', 'a' ]
}

expected

{
  type: 'object',
  kind: Symbol(ObjectKind),
  additionalProperties: false,
  properties: { a: { kind: Symbol(StringKind), type: 'string' } },
  required: [ 'a' ]
}

Got typescript error when using with recently released TS 3.9 and fast-json-stringify

TS 3.9 and fast-json-stringify^2.0.0

import { Type } from '@sinclair/typebox';
import fastJson from 'fast-json-stringify';

enum Enum {
  A = 'A',
  B = 'B',
  C = 'C',
}
const schema = Type.Object({
  param1: Type.String(),
  enum: Type.Enum(Enum, { type: 'string' }),
});

const stringify = fastJson(schema);  // <=== this string doesn't pass ts type validation
stringify({});

Workaround:

const schema = Type.Object({
  param1: Type.String(),
  enum: {
    enum: Object.values(Enum),
    type: 'string',
  },
});

Typescript types not working on Static

Hi!

I was following the doc and I was hoping that the following statement would work:

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

const ExampleType = {
  type: Type.Literal('location'),
  location: Type.Object({
    lat: Type.Number(),
    long: Type.Number(),
  }),
};
type ExampleType = Static<typeof ExampleType>;

function main(example: ExampleType) {
  example.type
}

main({ type: 'location', location: { lat: 1, long: 1 } })

But when I try to transpile with tsc, it gives me the following error:

$ npx tsc
index.ts:13:11 - error TS2339: Property 'type' does not exist on type 'unknown'.

13   example.type
             ~~~~

Found 1 error.

The IntelliSense doesn't recognize the ExampleType as a type as well.


Other informations:

package.json

  "dependencies": {
    "@sinclair/typebox": "^0.12.7"
  },
  "devDependencies": {
    "typescript": "^4.1.3"
  }

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "esnext",
    "module": "commonjs",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "outDir": "dist/",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "sourceMap": true
  }
}

Question: Enum and Unions

Hi, thanks for awesome project.

I have a question about union types and enums. We do not use ts enums because they are not supported in babel typescript. But for example such simple type:

type M = 'single' | 'married'

Could be expressed as:

{
type: 'string',
enum: ['single', 'married']
}

So that if i would write it like this with typebox:

const M = Type.Union([ Type.Literal('single'), Type.Literal('married') ])

/*
{
  kind: Symbol(UnionKind),
  anyOf: [
    { kind: Symbol(LiteralKind), type: 'string', enum: [Array] },
    { kind: Symbol(LiteralKind), type: 'string', enum: [Array] }
  ]
}
*/

so my suggestion is to allow to put union of literal values of the same type to be encoded as enum. WDYT?

Field descriptions

Is it possible to use typebox to generate JSON schemas with field descriptions?

For example:

"properties": {
    "productId": {
      "description": "The unique identifier for a product",
      "type": "integer"
    }
  }

Supplying default values

Hello! First off, great project, looks like a really interesting idea! I stumbled across it completely by accident while browsing the typescript subreddit, and its exactly the kind of thing I've been looking for to plug into Fastify (currently I'm manually syncing TS definitions and Schemas)

I couldn't see any way of defining default values. Is this something that I missed, or that you're planning on supporting? For example, how would the follow translate into a Typebox definition?

timeout: {
  type: 'number',
  minimum: 1000,
  maximum: 15000,
  default: 5000,
}

It seems like Type.Range(1000, 15000) mostly covers it, but not the default handler

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.