TS 中文文档 TS 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • 入门教程

    • TypeScript 手册
    • 基础知识
    • 日常类型
    • 类型缩小
    • 更多关于函数
    • 对象类型
    • 从类型创建类型
    • 泛型
    • Keyof 类型运算符
    • Typeof 类型运算符
    • 索引访问类型
    • 条件类型
    • 映射类型
    • 模板字面类型
    • 类
    • 模块
  • 参考手册

  • 项目配置

TypeBox


JSON Schema Type Builder with Static Type Resolution for TypeScript

undefined GitHub CI

Install


Npm


  1. ``` shell
  2. $ npm install @sinclair/typebox --save
  3. ```

Deno


  1. ``` ts
  2. import { Static, Type } from 'npm:@sinclair/typebox'
  3. ```

Esm


  1. ``` ts
  2. import { Static, Type } from 'https://esm.sh/@sinclair/typebox'
  3. ```

Example


  1. ``` ts
  2. import { Static, Type } from '@sinclair/typebox'

  3. const T = Type.Object({                              // const T = {
  4.   x: Type.Number(),                                  //   type: 'object',
  5.   y: Type.Number(),                                  //   required: ['x', 'y', 'z'],
  6.   z: Type.Number()                                   //   properties: {
  7. })                                                   //     x: { type: 'number' },
  8.                                                      //     y: { type: 'number' },
  9.                                                      //     z: { type: 'number' }
  10.                                                      //   }
  11.                                                      // }

  12. type T = Static<typeof T>                            // type T = {
  13.                                                      //   x: number,
  14.                                                      //   y: number,
  15.                                                      //   z: number
  16.                                                      // }
  17. ```

Overview


TypeBox is a runtime type builder that creates in-memory JSON Schema objects that can be statically inferred as TypeScript types. The schemas produced by this library are designed to match the static type assertion rules of the TypeScript compiler. TypeBox enables one to create a unified type that can be statically checked by TypeScript and runtime asserted using standard JSON Schema validation.

This library is designed to enable JSON schema to compose with the same flexibility as TypeScript's type system. It can be used as a simple tool to build up complex schemas or integrated into REST or RPC services to help validate data received over the wire.

License MIT

Contents


Install
Overview
Usage
Types
Standard
Extended
Modifiers
Options
Generics
References
Recursive
Conditional
Template Literal
Indexed
Rest
Guards
Unsafe
Strict

Values
Create
Clone
Check
Convert
Cast
Equal
Hash
Diff
Patch
Errors
Mutate
Pointer

TypeCheck
Ajv
TypeCompiler

TypeSystem
Types
Formats
Policies

Benchmark
Compile
Validate
Compression

Contribute

Usage


The following shows general usage.

  1. ``` ts
  2. import { Static, Type } from '@sinclair/typebox'

  3. //--------------------------------------------------------------------------------------------
  4. //
  5. // Let's say you have the following type ...
  6. //
  7. //--------------------------------------------------------------------------------------------

  8. type T = {
  9.   id: string,
  10.   name: string,
  11.   timestamp: number
  12. }

  13. //--------------------------------------------------------------------------------------------
  14. //
  15. // ... you can express this type in the following way.
  16. //
  17. //--------------------------------------------------------------------------------------------

  18. const T = Type.Object({                              // const T = {
  19.   id: Type.String(),                                 //   type: 'object',
  20.   name: Type.String(),                               //   properties: {
  21.   timestamp: Type.Integer()                          //     id: {
  22. })                                                   //       type: 'string'
  23.                                                      //     },
  24.                                                      //     name: {
  25.                                                      //       type: 'string'
  26.                                                      //     },
  27.                                                      //     timestamp: {
  28.                                                      //       type: 'integer'
  29.                                                      //     }
  30.                                                      //   },
  31.                                                      //   required: [
  32.                                                      //     'id',
  33.                                                      //     'name',
  34.                                                      //     'timestamp'
  35.                                                      //   ]
  36.                                                      // }

  37. //--------------------------------------------------------------------------------------------
  38. //
  39. // ... then infer back to the original static type this way.
  40. //
  41. //--------------------------------------------------------------------------------------------

  42. type T = Static<typeof T>                            // type T = {
  43.                                                      //   id: string,
  44.                                                      //   name: string,
  45.                                                      //   timestamp: number
  46.                                                      // }

  47. //--------------------------------------------------------------------------------------------
  48. //
  49. // ... then use the type both as JSON schema and as a TypeScript type.
  50. //
  51. //--------------------------------------------------------------------------------------------

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

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

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

  55.     // ok...
  56.   }
  57. }
  58. ```

Types


TypeBox types are JSON schema fragments that can be composed into more complex types. Each fragment is structured such that a JSON schema compliant validator can runtime assert a value the same way TypeScript will statically assert a type. TypeBox provides a set of Standard types which are used create JSON schema compliant schematics as well as an Extended type set used to create schematics for constructs native to JavaScript.

Standard Types


The following table lists the Standard TypeBox types. These types are fully compatible with the JSON Schema Draft 6 specification.

  1. ``` ts
  2. ┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐
  3. │ TypeBox                        │ TypeScript                  │ JSON Schema                    │
  4. │                                │                             │                                │
  5. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  6. │ const T = Type.Any()           │ type T = any                │ const T = { }                  │
  7. │                                │                             │                                │
  8. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  9. │ const T = Type.Unknown()       │ type T = unknown            │ const T = { }                  │
  10. │                                │                             │                                │
  11. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  12. │ const T = Type.String()        │ type T = string             │ const T = {                    │
  13. │                                │                             │   type: 'string'               │
  14. │                                │                             │ }                              │
  15. │                                │                             │                                │
  16. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  17. │ const T = Type.Number()        │ type T = number             │ const T = {                    │
  18. │                                │                             │   type: 'number'               │
  19. │                                │                             │ }                              │
  20. │                                │                             │                                │
  21. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  22. │ const T = Type.Integer()       │ type T = number             │ const T = {                    │
  23. │                                │                             │   type: 'integer'              │
  24. │                                │                             │ }                              │
  25. │                                │                             │                                │
  26. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  27. │ const T = Type.Boolean()       │ type T = boolean            │ const T = {                    │
  28. │                                │                             │   type: 'boolean'              │
  29. │                                │                             │ }                              │
  30. │                                │                             │                                │
  31. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  32. │ const T = Type.Null()          │ type T = null               │ const T = {                    │
  33. │                                │                             │   type: 'null'                 │
  34. │                                │                             │ }                              │
  35. │                                │                             │                                │
  36. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  37. │ const T = Type.Literal(42)     │ type T = 42                 │ const T = {                    │
  38. │                                │                             │   const: 42,                   │
  39. │                                │                             │   type: 'number'               │
  40. │                                │                             │ }                              │
  41. │                                │                             │                                │
  42. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  43. │ const T = Type.Array(          │ type T = number[]           │ const T = {                    │
  44. │   Type.Number()                │                             │   type: 'array',               │
  45. │ )                              │                             │   items: {                     │
  46. │                                │                             │     type: 'number'             │
  47. │                                │                             │   }                            │
  48. │                                │                             │ }                              │
  49. │                                │                             │                                │
  50. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  51. │ const T = Type.Object({        │ type T = {                  │ const T = {                    │
  52. │   x: Type.Number(),            │   x: number,                │   type: 'object',              │
  53. │   y: Type.Number()             │   y: number                 │   required: ['x', 'y'],        │
  54. │ })                             │ }                           │   properties: {                │
  55. │                                │                             │     x: {                       │
  56. │                                │                             │       type: 'number'           │
  57. │                                │                             │     },                         │
  58. │                                │                             │     y: {                       │
  59. │                                │                             │       type: 'number'           │
  60. │                                │                             │     }                          │
  61. │                                │                             │   }                            │
  62. │                                │                             │ }                              │
  63. │                                │                             │                                │
  64. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  65. │ const T = Type.Tuple([         │ type T = [number, number]   │ const T = {                    │
  66. │   Type.Number(),               │                             │   type: 'array',               │
  67. │   Type.Number()                │                             │   items: [{                    │
  68. │ ])                             │                             │      type: 'number'            │
  69. │                                │                             │   }, {                         │
  70. │                                │                             │     type: 'number'             │
  71. │                                │                             │   }],                          │
  72. │                                │                             │   additionalItems: false,      │
  73. │                                │                             │   minItems: 2,                 │
  74. │                                │                             │   maxItems: 2                  │
  75. │                                │                             │ }                              │
  76. │                                │                             │                                │
  77. │                                │                             │                                │
  78. ├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤
  79. │ enum Foo {                     │ enum Foo {                  │ const T = {                    │
  80. │   A,                           │   A,                        │   anyOf: [{                    │
  81. │   B                            │   B                         │     type: 'number',            │
  82. │ }                              │ }                           │     const: 0                   │
  83. │                                │                             │   }, {                         │
  84. │ const T = Type.Enum(Foo)       │ type T = Foo                │     type: 'number',            │
  85. │                                │                             │     const: 1                   │
  86. │                                │                             │   }]                           │
  87. │                                │                             │ }                              │
  88. │                                │                             │
Last Updated: 2023-09-03 17:10:52