💎 Zod 4 现已稳定发布! 阅读公告。
Zod logo

Zod

Edit this page

zod/v4 包是 Zod 生态系统的“旗舰”库。它在开发者体验和包体积之间取得了平衡,适用于绝大多数应用。

如果你对包体积有非常严格的要求,可以考虑使用 Zod Mini

Zod 致力于提供一个与 TypeScript 类型系统一一对应的 Schema API。

import * as z from "zod";
 
const schema = z.object({
  name: z.string(),
  age: z.number().int().positive(),
  email: z.email(),
});

该 API 依赖方法链,提供简洁、可链式调用且支持自动补全的方式来定义复杂类型。

z.string()
  .min(5)
  .max(10)
  .toLowerCase();

所有 Schema 都继承自 z.ZodType 基类,该类又继承自 zod/v4/core 中的 z.$ZodType。所有 ZodType 实例实现以下方法:

import * as z from "zod";
 
const mySchema = z.string();
 
// 解析
mySchema.parse(data);
mySchema.safeParse(data);
mySchema.parseAsync(data);
mySchema.safeParseAsync(data);
 
 
// 校验 refinements
mySchema.refine(refinementFunc);
mySchema.superRefine(refinementFunc); // 已弃用,使用 `.check()`
mySchema.overwrite(overwriteFunc);
 
// 包装器 wrappers
mySchema.optional();
mySchema.nonoptional();
mySchema.nullable();
mySchema.nullish();
mySchema.default(defaultValue);
mySchema.array();
mySchema.or(otherSchema);
mySchema.transform(transformFunc);
mySchema.catch(catchValue);
mySchema.pipe(otherSchema);
mySchema.readonly();
 
// 元数据和注册表 metadata and registries
mySchema.register(registry, metadata);
mySchema.describe(description);
mySchema.meta(metadata);
 
// 工具 utilities
mySchema.check(checkOrFunction);
mySchema.clone(def);
mySchema.brand<T>();
mySchema.isOptional(); // boolean
mySchema.isNullable(); // boolean