Skip to content

sinclairzx81/typebox

Repository files navigation

TypeBox

JSON Schema Type Builder with Static Type Resolution for TypeScript



npm version Downloads Build License

Install

$ npm install typebox

Usage

import Type from 'typebox'

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

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

Overview

Documentation

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

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

License: MIT

Contents

Type

Documentation | Example

TypeBox types are JSON Schema fragments that compose into more complex types. The library offers a set of types used to construct JSON Schema compliant schematics as well as a set of extended types used to model constructs native to the JavaScript language. The schematics produced by TypeBox can be passed directly to any JSON Schema compliant validator.

Example

The following creates a User type and infers with Static.

import Type from 'typebox'

// Type

const User = Type.Object({                       // const User = {
  id: Type.String(),                             //   type: 'object',
  name: Type.String(),                           //   properties: {
  email: Type.String({ format: 'email' })        //     id: { type: 'string' },
})                                               //     name: { type: 'string' },
                                                 //     email: { 
                                                 //       type: 'string', 
                                                 //       format: 'email' 
                                                 //     }
                                                 //   }
                                                 //   required: [
                                                 //     'id', 
                                                 //     'name', 
                                                 //     'email'
                                                 //   ]
                                                 // }

// Static

type User = Type.Static<typeof User>              // type User = {
                                                  //   id: string,
                                                  //   name: string,
                                                  //   email: string
                                                  // }

Script

Documentation | Example 1 | Example 2

TypeBox includes a micro DSL for composing JSON Schema with TypeScript syntax. The DSL offers a full syntactic frontend to Type.* and supports many advanced type-level constructs such as Conditional, Mapped, Indexed, Infer, Generics, Distributed types and more. This feature is implemented symmetrically at runtime and statically via TypeScript Template Literal types.

Example

The following uses Script to parse a TypeScript definition module into JSON Schema.

import Type from 'typebox'

// Script

const { User, UserUpdate } = Type.Script(`

  interface Entity {
    id: string
  }

  interface User extends Entity { 
    name: string, 
    email: string 
  }

  type UserUpdate = Evaluate<
    Pick<User, keyof Entity> & 
    Partial<Omit<User, keyof Entity>>
  >

`)

// Reflect

console.log(User)                                // {
                                                 //   type: 'object',
                                                 //   properties: {
                                                 //     id: { type: 'string' },
                                                 //     name: { type: 'string' },
                                                 //     email: { type: 'string' }
                                                 //   },
                                                 //   required: [
                                                 //     'id', 
                                                 //     'name', 
                                                 //     'email'
                                                 //   ]
                                                 // }

console.log(UserUpdate)                          // {
                                                 //   type: 'object',
                                                 //   properties: {
                                                 //     id: { type: 'string' },
                                                 //     name: { type: 'string' },
                                                 //     email: { type: 'string' }
                                                 //   },
                                                 //   required: ['id']
                                                 // }

// Static

type User = Type.Static<typeof User>              // type User = {
                                                  //   id: string,
                                                  //   name: string,
                                                  //   email: string
                                                  // }

type UserUpdate = Type.Static<typeof UserUpdate>  // type UserUpdate = {
                                                  //   id: string,
                                                  //   name?: string,
                                                  //   email?: string
                                                  // }

Schema

Documentation | Example 1 | Example 2

TypeBox includes a high-performance JIT compiler that supports JSON Schema Draft 3 through to 2020-12. It is designed to be a lightweight industry-grade alternative to Ajv and offers improved compilation and validation performance. It also provides automatic fallback to dynamic validation in JIT restricted environments such as Cloudflare Workers.

The compiler is available via optional sub module import.

import Schema from 'typebox/schema'

Compile

The compiler accepts JSON Schema and returns Validator instances.

const Vector = Schema.Compile(Type.Object({       // const Vector: Validator<TObject<{
  x: Type.Number(),                                //   x: TNumber
  y: Type.Number(),                                //   y: TNumber
  z: Type.Number()                                 //   z: TNumber
}))                                                // }>>

With JSON Schema

const Vector = Schema.Compile({                    // const Vector: Validator<{
  type: 'object',                                  //   type: "object";
  required: ['x', 'y', 'z'],                       //   required: ["x", "y", "z"];
  properties: {                                    //   properties: { ... };
    x: { type: 'number' },                         // }, { ... }>
    y: { type: 'number' },
    z: { type: 'number' }
  }
})

Validate

Validator instances provide functions to Check and Parse values.

const Vector = Schema.Compile(Type.Script(`{
  x: number
  y: number
  z: number
}`))

const valid = Vector.Check({                       // const valid: boolean
  x: 1,
  y: 0,
  z: 0
}) 

const value = Vector.Parse({                       // const value: {      
  x: 1,                                            //   x: number
  y: 0,                                            //   y: number
  z: 0                                             //   z: number
})                                                 // }

Coverage

The following table shows specification coverage implemented by TypeBox.

Ref: JSON Schema Test Suite

Spec 3 4 6 7 2019-09 2020-12 v1
additionalItems - -
additionalProperties
allOf -
anchor - - - -
anyOf -
boolean_schema - -
const - -
contains - -
content - - - -
default
dependencies 17/18 - - -
dependentRequired - - - -
dependentSchemas - - - -
dynamicRef - - - - - 38/44 19/27
enum 14/16
exclusiveMaximum - -
exclusiveMinimum - -
if-then-else - - -
infinite-loop-detection
items
maxContains - - - -
maximum 13/14 13/14
maxItems
maxLength
maxProperties -
minContains - - - -
minimum 12/13 16/17
minItems
minLength
minProperties -
multipleOf -
not -
oneOf -
pattern
patternProperties
prefixItems - - - - -
properties
propertyNames - -
recursiveRef - - - - - -
ref 23/27 37/45 67/70 75/78 79/81 77/79 77/79
required 3/4
type 73/80
unevaluatedItems - - - - 65/71 64/71
unevaluatedProperties - - - - 124/125
uniqueItems

Performance

The following table shows compile performance for various JSON Schema structures using AJV8 as a basis for comparison.

┌──────────────────────┬─────────────┬─────────────┐
│ CompileTB1XAJV8        │
├──────────────────────┼─────────────┼─────────────┤
│ Boolean29.2K ops/s7.1K ops/s │
│ Number34.5K ops/s7.6K ops/s │
│ String48.9K ops/s8.7K ops/s │
│ Null39.6K ops/s7.6K ops/s │
│ Literal_String46.8K ops/s6.8K ops/s │
│ Literal_Number48.3K ops/s7.4K ops/s │
│ Literal_Boolean48.8K ops/s7.3K ops/s │
│ Pattern32.5K ops/s6.1K ops/s │
│ Object_Open6.6K ops/s1.4K ops/s │
│ Object_Close7.6K ops/s1K ops/s │
│ Object_Vector320.8K ops/s2.8K ops/s │
│ Object_Basis37.5K ops/s1K ops/s │
│ Intersect_And23K ops/s3.9K ops/s │
│ Intersect_Structural8.7K ops/s1.2K ops/s │
│ Union_Or17.9K ops/s3.4K ops/s │
│ Union_Structural11.3K ops/s2.1K ops/s │
│ Tuple_Values9.6K ops/s2.1K ops/s │
│ Tuple_Objects2.1K ops/s350 ops/s │
│ Array_Numbers_433.6K ops/s4.2K ops/s │
│ Array_Numbers_839K ops/s3.7K ops/s │
│ Array_Numbers_1629.6K ops/s3.8K ops/s │
│ Array_Objects_Open7.7K ops/s833 ops/s │
│ Array_Objects_Close7.6K ops/s860 ops/s │
└──────────────────────┴─────────────┴─────────────┘

The following tables shows validation performance for various JSON Schema structures using AJV8 as a basis for comparison.

┌──────────────────────┬──────────────┬──────────────┐
│ ValidateTB1XAJV8         │
├──────────────────────┼──────────────┼──────────────┤
│ Boolean192.2M ops/s189.5M ops/s │
│ Number112.4M ops/s61M ops/s │
│ String113.7M ops/s64.1M ops/s │
│ Null112.8M ops/s64.9M ops/s │
│ Literal_String108M ops/s62.9M ops/s │
│ Literal_Number113.5M ops/s63.2M ops/s │
│ Literal_Boolean109.2M ops/s64.1M ops/s │
│ Pattern26.5M ops/s22.4M ops/s │
│ Object_Open78M ops/s47.2M ops/s │
│ Object_Close38.6M ops/s27.6M ops/s │
│ Object_Vector391M ops/s51.3M ops/s │
│ Object_Basis341.1M ops/s27.4M ops/s │
│ Intersect_And107.6M ops/s59.9M ops/s │
│ Intersect_Structural83.6M ops/s46.3M ops/s │
│ Union_Or95M ops/s7.9M ops/s │
│ Union_Structural84.5M ops/s52.3M ops/s │
│ Tuple_Values74.7M ops/s53M ops/s │
│ Tuple_Objects32.9M ops/s22.3M ops/s │
│ Array_Numbers_493.3M ops/s55.1M ops/s │
│ Array_Numbers_890.3M ops/s50.8M ops/s │
│ Array_Numbers_1676.8M ops/s39.6M ops/s │
│ Array_Objects_Open28.7M ops/s20.4M ops/s │
│ Array_Objects_Close10.3M ops/s10.8M ops/s │
└──────────────────────┴──────────────┴──────────────┘

Versions

TypeBox ships two distinct versions that span two generations of the TypeScript compiler.

TypeBox TypeScript Description
1.x 6.0 - 7.0+ Latest. Developed against the TypeScript 7 native compiler. Provides advanced type inference and native JSON Schema 2020-12 support. Includes backwards compatibility with 0.x types. ESM only.
0.x 5.0 - 6.0 LTS. Developed against older TypeScript versions and actively maintained under Long Term Support. Compatible with both ESM and CJS. Issues should be submitted to the Sinclair TypeBox repository.

Contribute

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

About

JSON Schema Type Builder with Static Type Resolution for TypeScript

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages