💎 Zod 4 is now stable!  Read the announcement.
Zod logo

Zod

zod/v4 包是 Zod 生態系統的「旗艦」庫。它在開發人員體驗和包大小之間取得了平衡,非常適合絕大多數應用程序。

如果您對包大小有異常嚴格的限制,請考慮 Zod Mini

Zod 旨在提供一個與 TypeScript 類型系統一對一映射的架構 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();

所有架構都擴展 z.ZodType 基類,該基類又擴展 zod/v4/core 中的 z.$ZodTypeZodType 的所有實例都實現以下方法:

import * as z from "zod";
 
const mySchema = z.string();
 
// parsing
mySchema.parse(data);
mySchema.safeParse(data);
mySchema.parseAsync(data);
mySchema.safeParseAsync(data);
 
 
// refinements
mySchema.refine(refinementFunc);
mySchema.superRefine(refinementFunc); // deprecated, use `.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