TypeBox 入门:JSON Schema 驱动的类型安全校验
TypeBox 一份 Schema 同时产出 TypeScript 类型与 JSON Schema:运行时校验与编译期类型双安全。本文讲解 Schema 定义、类型推导与自定义校验。
TypeBox 用 Type.Object({ name: Type.String() }) 定义 Schema——Static<typeof S> 得到 TS 类型,Schema 本身是标准 JSON Schema(可直接用于 OpenAPI/Fastify)。校验用 Value.Check() 或编译器加速。类型与校验同源是它的核心卖点。
快速上手
npm install @sinclair/typebox
import { Type, Static } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
const User = Type.Object({
name: Type.String({ minLength: 1 }),
email: Type.String({ format: 'email' }),
age: Type.Optional(Type.Integer({ minimum: 0 })),
});
type User = Static<typeof User>;
// { name: string; email: string; age?: number }——类型自动推导
Value.Check(User, data); // boolean
const errors = [...Value.Errors(User, data)]; // 详细错误列表
组合能力
const Post = Type.Object({
title: Type.String(),
author: User, // 嵌套
tags: Type.Array(Type.String(), { maxItems: 5 }),
status: Type.Union([Type.Literal('draft'), Type.Literal('published')]),
meta: Type.Nullable(Type.Record(Type.String(), Type.String())),
});
Union/Intersect/Partial/Pick/Record——TS 类型操作在 Schema 层基本都有对应。
自定义格式与校验
import { FormatRegistry } from '@sinclair/typebox';
FormatRegistry.Set('phone', (v) => /^1[3-9]\d{9}$/.test(v));
Type.String({ format: 'phone' });
性能与编译
TypeCompiler 把 Schema 编译为特化校验函数——大数据量/高频校验场景的性能答案:
import { TypeCompiler } from '@sinclair/typebox/compiler';
const check = TypeCompiler.Compile(User);
check.Check(data);
常见问题(FAQ)
Q:TypeBox 和 Zod 怎么选?
需要标准 JSON Schema 输出(OpenAPI 文档、Fastify 集成)选 TypeBox;纯应用内校验、生态集成(tRPC/RHF)选 Zod。详见本系列对比文章。
Q:能用于 Fastify 吗?
TypeBox 是 Fastify 类型化 Schema 的官方推荐搭配——Schema 同时是校验规则与 TS 类型,一体两面。
Q:错误信息能中文化吗?
Value.Errors 返回结构化错误(path + message),可自定义映射层转换为业务语言。
参考文档
本文依据公开文档整理,示例需按项目依赖版本验证;不将文档中的性能描述视为本项目实测结果。