SuperAPI AI 工具集

zod

编程与开发

查看项目

更新于 10-15 21:38

技能介绍

Zod 是 TypeScript 优先的 schema 校验库,具备静态类型推断能力:定义一次 schema 即可同时得到运行时校验和 TypeScript 类型(通过 z.infer),零外部依赖,可在 Node 与浏览器中运行,适合表单、API 解析、环境变量及各类不可信输入。建议 TypeScript 5.5+ 并在 tsconfig.json 中启用 strict。安装可通过包管理器添加 zod,详见 zod.dev。

主要能力:支持 z.string()、z.number()、z.boolean()、z.date()、z.literal、z.enum 等基础类型,以及 .email()、.url()、.uuid()、.int()、.min()/.max() 等约束;支持 .optional()、.nullable()、.nullish()、.default()。对象支持 .shape、.keyof()、.extend()、.pick()/.omit()、.partial()/.required()、.strict()、.catchall(),并可用 z.lazy() 构建递归结构。还支持数组、元组、联合、交叉、可辨识联合 z.discriminatedUnion、.refine()/.superRefine() 自定义校验、.transform()、.pipe() 等。

用法:使用 .parse(input) 返回数据或抛出 ZodError,.safeParse(input) 返回 { success, data } 或 { success: false, error };异步校验用 .parseAsync/.safeParseAsync。错误可通过 error.issues(含 path、message、code)和 error.format() 读取。类型推断方面,z.infer 得到输出类型,z.input 得到转换前输入类型,z.output 与 z.infer 相同。

与 React Hook Form 集成时,可配合 @hookform/resolvers 的 zodResolver 使用。最佳实践包括:API 边界优先严格 schema、必要时用 .passthrough() 转发未知键;对可选字段使用 .default();API/环境变量解析使用 safeParse 并处理 error.issues;变体负载使用可辨识联合;仅在安全时使用 z.coerce 或自定义 transform。常见误区包括忽略 strict、混淆输入与输出类型、在热路径频繁 parse、schema 过于宽泛。官方资源见 https://zod.dev 及 https://zod.dev/api。