佐德语Name
TypeScript- first schema 验证并采用静态类型推论
以 @colinhacks (英语)
赞助人:爵士乐
阅读文件 {}
佐德是谁?
Zod是一个TypeScript-First验证库. 定义一个计划并分析一些数据。 你会得到一个强烈打字, 验证的结果.
import * as z from "zod";
const User = z.object({
name: z.string(),
});
// some untrusted data...
const input = {
/* stuff */
};
// the parsed result is validated and type safe!
const data = User.parse(input);
// so you can use it with confidence :)
console.log(data.name);
特征
- 外部依赖性为零
- 在Node.js和所有现代浏览器中工作
- 小声:
2kb核心捆绑( gzip) - 不可移动 API: 方法返回新实例
- 简洁界面
- 与TypeScript和普通JS合作
- 内建 JSON Schema 转换
- 广泛的生态系统
安装
npm install zod
基本用途
在你可以做其他事情之前,需要定义一个计划. 为了本指南的目的,我们将使用简单的对象计划.
import * as z from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
分析数据
考虑到Zod计划,使用 .parse 以验证输入。 如果有效, Zod 返回强烈类型 深克隆 输入.
Player.parse({ username: "billie", xp: 100 });
// => returns { username: "billie", xp: 100 }
说明 -如果您的计划使用某种同步的 API 如 async 改进 或者说 变换,你将需要使用 .parseAsync() 方法代替.
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.parseAsync("hello");
// => "hello"
处理错误
当验证失败时 .parse() 方法将丢出一个 ZodError 实例中包含关于验证问题的颗粒信息.
try {
Player.parse({ username: 42, xp: "100" });
} catch (err) {
if (err instanceof z.ZodError) {
err.issues;
/* [
{
expected: 'string',
code: 'invalid_type',
path: [ 'username' ],
message: 'Invalid input: expected string'
},
{
expected: 'number',
code: 'invalid_type',
path: [ 'xp' ],
message: 'Invalid input: expected number'
}
] */
}
}
为了避免 try/catch 块,您可以使用 .safeParse() 方法以获取包含成功解析数据或a的纯结果对象 ZodError。结果类型是 受歧视的工会来方便地处理这两个案子.
const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
result.error; // ZodError instance
} else {
result.data; // { username: string; xp: number }
}
说明 -如果您的计划使用某种同步的 API 如 async 改进 或者说 变换,你将需要使用 .safeParseAsync() 方法代替.
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.safeParseAsync("hello");
// => { success: true; data: "hello" }
推断类型
Zod从你的计划定义推断出一种静态类型. 您可以用 z.infer<> 有用,随便你用.
const Player = z.object({
username: z.string(),
xp: z.number(),
});
// extract the inferred type
type Player = z.infer<typeof Player>;
// use it in your code
const player: Player = { username: "billie", xp: 100 };
在某些情况下,一个计划的输入和输出类型可能有所不同. 例如 .transform() API可以将输入从一种类型转换到另一种类型. 在这种情况下,您可以独立提取输入和输出类型:
const mySchema = z.string().transform((val) => val.length);
type MySchemaIn = z.input<typeof mySchema>;
// => string
type MySchemaOut = z.output<typeof mySchema>; // equivalent to z.infer<typeof mySchema>
// number