基本用法
| 维度 | Zod | Zod Mini |
|---|---|---|
| 包体积 | 较大(~30kb+ gzip) | 非常小(~5kb gzip 左右) |
| API 完整度 | 完整 | 子集 |
| refine / transform | ✅ 支持 | ❌ 不支持 |
| async 校验 | ✅ | ❌ |
| error 结构 | 详细、可定制 | 简化 |
| infer 类型 | ✅ | ✅ |
| 运行环境 | Node / Browser | Edge / Worker / 小程序友好 |
| 设计目标 | 功能优先 | 体积 & 性能优先 |
基础用法
- 创建 schema
- 通过 schema 验证
- 处理结果
处理结果有两种方式
- 通过
.parse()返回验证对象的“深拷贝”,错误时.parse()会抛出一个 ZodError - 通过
.safeParse()中 success 得知是否成功
ts
import * as z from "zod/v4";
// import { z } from "zod/v4";
import zhCN from "zod/v4/locales/zh-CN.js";
// 使用中文
z.config(zhCN());
const Player = z.object({
account: z.string({ error: "账号不能为空" }),
password: z.string({ error: "密码不能为空" }),
});
const data = Player.parse({});推断类型
提取所定义的 schema 的 ts 类型
ts
type Player = z.infer<typeof Player>;类型不一致时
todo
ts
const mySchema = z.string().transform((val) => val.length);
type MySchemaIn = z.input<typeof mySchema>;
// => string
type MySchemaOut = z.output<typeof mySchema>; // 等同于 z.infer<typeof mySchema>
// number