Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@catchfashion/typebox

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@catchfashion/typebox

JSONSchema Type Builder with Static Type Resolution for TypeScript

  • 1.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

TypeBox

JSON Schema Type Builder with Static Type Resolution for TypeScript

npm version GitHub CI

Install

$ npm install @sinclair/typebox --save

Overview

TypeBox is a type builder library that allows developers to compose in-memory JSON Schema objects that can be statically resolved to TypeScript types. The schemas produced by TypeBox can be used directly as validation schemas or reflected upon by navigating the standard JSON Schema properties at runtime. TypeBox can be used as a simple tool to build up complex schemas or integrated into RPC or REST services to help validate JSON data received over the wire.

TypeBox does not provide any mechanism for validating JSON Schema. Please refer to libraries such as AJV or similar to validate the schemas created with this library.

Requires TypeScript 3.8.3 and above.

License MIT

Contents

Example

The following shows the general usage.

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

// some type ...

type Order = {
    email:    string,
    address:  string,
    quantity: number,
    option:   'pizza' | 'salad' | 'pie'
}

// ... can be expressed as ...

const Order = Type.Object({
    email:    Type.String({ format: 'email' }), 
    address:  Type.String(),
    quantity: Type.Number({ minimum: 1, maximum: 99 }),
    option:   Type.Union([
        Type.Literal('pizza'), 
        Type.Literal('salad'),
        Type.Literal('pie')
    ])
})

// ... which can be reflected

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

// ... and statically resolved

type TOrder = Static<typeof Order>

// .. and validated as JSON Schema

JSON.validate(Order, {  // IETF | TC39 ?
    email: 'dave@domain.com', 
    address: '...', 
    quantity: 99, 
    option: 'pie' 
}) 

// ... and so on ...

Types

TypeBox provides a number of functions to generate JSON Schema data types. The following tables list the functions TypeBox provides and their respective TypeScript and JSON Schema equivalents.

TypeBox > TypeScript

TypeTypeBoxTypeScript
Literalconst T = Type.Literal(123)type T = 123
Stringconst T = Type.String()type T = string
Numberconst T = Type.Number()type T = number
Integerconst T = Type.Integer()type T = number
Booleanconst T = Type.Boolean()type T = boolean
Objectconst T = Type.Object({ name: Type.String() })type T = { name: string }
Arrayconst T = Type.Array(Type.Number())type T = number[]
Mapconst T = Type.Map(Type.Number())type T = { [key: string] } : number
Intersectconst T = Type.Intersect([Type.String(), Type.Number()])type T = string & number
Unionconst T = Type.Union([Type.String(), Type.Number()])type T = string | number
Tupleconst T = Type.Tuple([Type.String(), Type.Number()])type T = [string, number]
Anyconst T = Type.Any()type T = any
Nullconst T = Type.Null()type T = null
Patternconst T = Type.Pattern(/foo/)type T = string
Guidconst T = Type.Guid()type T = string

TypeBox > JSON Schema

TypeTypeBoxJSON Schema
Literalconst T = Type.Literal(123){ type: 'number', enum: [123] }
Stringconst T = Type.String(){ type: 'string' }
Numberconst T = Type.Number(){ type: 'number' }
Integerconst T = Type.Number(){ type: 'integer' }
Booleanconst T = Type.Boolean(){ type: 'boolean' }
Objectconst T = Type.Object({ name: Type: String() }){ type: 'object': properties: { name: { type: 'string' } }, required: ['name'] }
Arrayconst T = Type.Array(Type.String()){ type: 'array': items: { type: 'string' } }
Mapconst T = Type.Map(Type.Number()){ type: 'object', additionalProperties: { type: 'number' } }
Intersectconst T = Type.Intersect([Type.Number(), Type.String()]){ allOf: [{ type: 'number'}, {type: 'string'}] }
Unionconst T = Type.Union([Type.Number(), Type.String()]){ oneOf: [{ type: 'number'}, {type: 'string'}] }
Tupleconst T = Type.Tuple([Type.Number(), Type.String()]){ type: "array", items: [{type: 'string'}, {type: 'number'}], additionalItems: false, minItems: 2, maxItems: 2 }
Anyconst T = Type.Any(){ }
Nullconst T = Type.Null(){ type: 'null' }
Patternconst T = Type.Pattern(/foo/){ type: 'string', pattern: 'foo' }
Guidconst T = Type.Guid(){ type: 'string', pattern: '<guid-regex>' }

Type Modifiers

The following are object property modifiers. Note that Type.Optional(...) will make the schema object property optional. Type.Readonly(...) however has no effect on the underlying schema as is only meaningful to TypeScript.

TypeTypeBoxTypeScript
Readonlyconst T = Type.Object({ email: Type.Readonly(Type.String()) })type T = { readonly email: string }
Optionalconst T = Type.Object({ email: Type.Optional(Type.String()) })type T = { email?: string }

Enums

It is possible to define TypeScript enums and use them as part of your TypeBox schema. Both number and string-valued enums are supported.

enum Color {
    Red = 'red',
    Blue = 'blue'
}

const T = Type.Enum(Color); // -> json-schema: `{ enum: ['red','green'] }`

Note that the generated json-schema will only permit the values of the enum, not its keys. In TypeScript, if you omit the value for an enum option, TypeScript will implicitly assign the option a numeric value.

E.g.:

enum Color {
    Red, // implicitly gets value `0`
    Blue // implicitly gets value `1`
}

const T = Type.Enum(Color); // -> json-schema: `{ enum: [0, 1] }`

User Defined Schema Properties

It's possible to specify custom properties on schemas. The last parameter on each TypeBox function accepts an optional UserDefinedOptions object. Properties specified in this object will appear as properties on the resulting schema object. Consider the following.

const T = Type.Object({
    value: Type.String({ 
        description: 'A required string.'
    })
}, {
    description: 'An object with a value'
})
{
  "description": "An object with a value",
  "type": "object",
  "properties": {
    "value": {
      "description": "A required string.",
      "type": "string"
    }
  },
  "required": [
    "value"
  ]
}

Function Types

TypeBox allows function signatures to be composed in a similar way to other types, but uses a custom schema format to achieve this. Note, this format is not JSON Schema, rather it embeds JSON Schema to encode function arguments and return types. The format also provides additional types not present in JSON Schema; Type.Constructor(), Type.Void(), Type.Undefined(), and Type.Promise().

For more information on using functions, see the Functions and Generics sections below.

Format

The following is an example of how TypeBox encodes function signatures.

type T = (a: string, b: number) => boolean

{
    "type": "function",
    "returns": { "type": "boolean" },
    "arguments": [
        {"type": "string" }, 
        {"type": "number" },
    ]
}

TypeBox > TypeScript

IntrinsicTypeBoxTypeScript
Functionconst T = Type.Function([Type.String()], Type.String())type T = (arg0: string) => string
Constructorconst T = Type.Constructor([Type.String()], Type.String())type T = new (arg0: string) => string
Promiseconst T = Type.Promise(Type.String())type T = Promise<string>
Undefinedconst T = Type.Undefined()type T = undefined
Voidconst T = Type.Void()type T = void

TypeBox > JSON Function

IntrinsicTypeBoxJSON Function
Functionconst T = Type.Function([Type.String()], Type.Number()){ type: 'function', arguments: [ { type: 'string' } ], returns: { type: 'number' } }
Constructorconst T = Type.Constructor([Type.String()], Type.Number()){ type: 'constructor', arguments: [ { type: 'string' } ], returns: { type: 'number' } }
Promiseconst T = Type.Promise(Type.String()){ type: 'promise', item: { type: 'string' } }
Undefinedconst T = Type.Undefined(){ type: 'undefined' }
Voidconst T = Type.Void(){ type: 'void' }

Functions

The following demonstrates creating function signatures for the following TypeScript types.

TypeScript

type T0 = (a0: number, a1: string) => boolean;

type T1 = (a0: string, a1: () => string) => void;

type T2 = (a0: string) => Promise<number>;

type T3 = () => () => string;

type T4 = new () => string

TypeBox

const T0 = Type.Function([Type.Number(), Type.String()], Type.Boolean())

const T1 = Type.Function([Type.String(), Type.Function([], Type.String())], Type.Void())

const T2 = Type.Function([Type.String()], Type.Promise(Type.Number()))

const T3 = Type.Function([], Type.Function([], Type.String()))

const T4 = Type.Constructor([], Type.String())

Generics

Generic function signatures can be composed with TypeScript functions with Generic Constraints.

TypeScript

type ToString = <T>(t: T) => string

TypeBox

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

const ToString = <G extends TStatic>(T: G) => Type.Function([T], Type.String())

However, it's not possible to statically infer what type ToString is without first creating some specialized variant of it. The following creates a specialization called NumberToString.

const NumberToString = ToString(Type.Number())

type X = Static<typeof NumberToString>

// X is (arg0: number) => string

To take things a bit further, the following code contains some generic TypeScript REST setup with controllers that take some generic resource of type T. Below this we express that same setup using TypeBox. The resulting type IRecordController contains reflectable interface metadata about the RecordController.

TypeScript

interface IController<T> {
    get    (): Promise<T>
    post   (resource: T): Promise<void>
    put    (resource: T): Promise<void>
    delete (resource: T): Promise<void>
}

interface Record {
     key: string
     value: string
}

class RecordController implements IController<Record> {
    async get   (): Promise<Record> { throw 'not implemented' }
    async post  (resource: Record): Promise<void> { /* */  }
    async put   (resource: Record): Promise<void> { /* */  }
    async delete(resource: Record): Promise<void> { /* */  }
}

TypeBox

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

const IController = <G extends TStatic>(T: G) => Type.Object({
    get:    Type.Function([], Type.Promise(T)),
    post:   Type.Function([T], Type.Promise(Type.Void())),
    put:    Type.Function([T], Type.Promise(Type.Void())),
    delete: Type.Function([T], Type.Promise(Type.Void())),
})

type Record = Static<typeof Record>
const Record = Type.Object({
    key: Type.String(),
    value: Type.String()
})

type IRecordController = Static<typeof IRecordController>
const IRecordController = IController(Record)

class RecordController implements IRecordController {
    async get   (): Promise<Record> { throw 'not implemented' }
    async post  (resource: Record): Promise<void> { /* */  }
    async put   (resource: Record): Promise<void> { /* */  }
    async delete(resource: Record): Promise<void> { /* */  }
}

// Reflect
console.log(IRecordController)

Validation

The following uses the library Ajv to validate a type.

import * Ajv from 'ajv'

const ajv = new Ajv({ })

ajv.validate(Type.String(), 'hello')  // true

ajv.validate(Type.String(), 123)      // false

Keywords

FAQs

Package last updated on 17 Sep 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc