佐德
✨ https://zod.dev ✨
使用静态类型推断进行 TypeScript 优先模式验证
这些文档已翻译成中文。
目录
简介
Zod 是一个 TypeScript 优先的架构声明和验证库。我使用术语“架构”广泛地指代任何数据类型,从简单的字符串到复杂的嵌套对象。
Zod 的设计目标是尽可能对开发人员友好。目标是消除重复的类型声明。使用 Zod,您声明一个验证器一次,Zod 将自动推断静态 TypeScript 类型。将更简单的类型组合成复杂的数据结构很容易。
其他一些伟大的方面:
- 零依赖
- 适用于 Node.js 和所有现代浏览器
- 微小:8kb 缩小 + 压缩
- 不可变:方法(即
.Optional()
)返回一个新实例
- 简洁、可链接的界面
- 功能方法: 解析,不验证
- 也适用于纯 JavaScript !您不需要使用 TypeScript。
我们赞赏并鼓励任何级别的赞助。对于个人开发者,请考虑一杯咖啡。如果您使用 Zod 构建了付费产品,请考虑讲台层之一。
金子
银
青铜
生态系统
有越来越多的工具构建于 Zod 之上或原生支持 Zod!如果您在 Zod 之上构建了工具或库,请在 Twitter 或 开始讨论。我将在下面添加它并发布推文。
资源
API 库
Zod to X
X 到 Zod
模拟
由 Zod 提供支持
slonik
:具有强大 Zod 集成的 Node.js Postgres 客户端。
-
soly
:使用 zod 创建 CLI 应用程序。
-
zod-xlsx
:使用 Zod 架构的基于 xlsx 的资源验证器。
安装
要求
- TypeScript 4.1+!
- 您必须在 tsconfig.json 中启用严格模式。这是所有 TypeScript 项目的最佳实践。
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}
来自 npm
(Node/Bun)
npm install zod # npm
yarn add zod # yarn
bun add zod # bun
pnpm add zod # pnpm
来自 deno.land/x
(Deno)
与 Node 不同,Deno 依赖于直接 URL 导入,而不是像 NPM 这样的包管理器。 Zod 可在 deno.land/x 上使用。可以像这样导入最新版本:
import { z } from "https://deno.land/x/zod/mod.ts";
您还可以指定特定版本:
import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts";
本自述文件的其余部分假设您使用 npm 并直接从 "zod"
包导入。
基本用法
创建简单字符串模式
import { z } from "zod";
// creating a schema for strings
const mySchema = z.string();
// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError
// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }
创建对象模式
import { z } from "zod";
const User = z.object({
username: z.string(),
});
User.parse({ username: "Ludwig" });
// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }
基元
import { z } from "zod";
// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();
// empty types
z.undefined();
z.null();
z.void(); // accepts undefined
// catch-all types
// allows any value
z.any();
z.unknown();
// never type
// allows no values
z.never();
文字
const tuna = z.literal("tuna");
const twelve = z.literal(12);
const twobig = z.literal(2n); // bigint literal
const tru = z.literal(true);
const terrificSymbol = Symbol("terrific");
const terrific = z.literal(terrificSymbol);
// retrieve literal value
tuna.value; // "tuna"
目前,Zod 中不支持日期文本。如果您有此功能的用例,请提出问题。
字符串
Zod 包含一些特定于字符串的验证。
z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().email();
z.string().url();
z.string().uuid();
z.string().cuid();
z.string().regex(regex);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().trim(); // trim whitespace
z.string().datetime(); // defaults to UTC, see below for options
查看validator.js,了解许多其他有用的字符串验证函数,这些函数可以与改进。
您可以在创建字符串架构时自定义一些常见错误消息。
const name = z.string({
required_error: "Name is required",
invalid_type_error: "Name must be a string",
});
使用验证方法时,您可以传入附加参数来提供自定义错误消息。
z.string().min(5, { message: "Must be 5 or more characters long" });
z.string().max(5, { message: "Must be 5 or fewer characters long" });
z.string().length(5, { message: "Must be exactly 5 characters long" });
z.string().email({ message: "Invalid email address" });
z.string().url({ message: "Invalid url" });
z.string().uuid({ message: "Invalid UUID" });
z.string().startsWith("https://", { message: "Must provide secure URL" });
z.string().endsWith(".com", { message: "Only .com domains allowed" });
z.string().datetime({ message: "Invalid datetime string! Must be UTC." });
日期时间验证
z.string().datetime()
方法默认使用 UTC 验证:没有具有任意亚秒小数精度的时区偏移。
const datetime = z.string().datetime();
datetime.parse("2020-01-01T00:00:00Z"); // pass
datetime.parse("2020-01-01T00:00:00.123Z"); // pass
datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision)
datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed)
通过将 offset
选项设置为 true
可以允许时区偏移。
const datetime = z.string().datetime({ offset: true });
datetime.parse("2020-01-01T00:00:00+02:00"); // pass
datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional)
datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported)
您还可以限制允许的精度
。默认情况下,支持任意亚秒精度(但可选)。
const datetime = z.string().datetime({ precision: 3 });
datetime.parse("2020-01-01T00:00:00.123Z"); // pass
datetime.parse("2020-01-01T00:00:00Z"); // fail
datetime.parse("2020-01-01T00:00:00.123456Z"); // fail
数字
您可以在创建数字架构时自定义某些错误消息。
const age = z.number({
required_error: "Age is required",
invalid_type_error: "Age must be a number",
});
Zod 包含一些特定于数字的验证。
z.number().gt(5);
z.number().gte(5); // alias .min(5)
z.number().lt(5);
z.number().lte(5); // alias .max(5)
z.number().int(); // value must be an integer
z.number().positive(); // > 0
z.number().nonnegative(); // >= 0
z.number().negative(); // < 0
z.number().nonpositive(); // <= 0
z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5)
z.number().finite(); // value must be finite, not Infinity or -Infinity
或者,您可以传入第二个参数来提供自定义错误消息。
z.number().lte(5, { message: "this????is????too????big" });
NaN
您可以在创建 nan 模式时自定义某些错误消息。
const isNaN = z.nan({
required_error: "isNaN is required",
invalid_type_error: "isNaN must be not a number",
});
布尔值
您可以在创建布尔模式时自定义某些错误消息。
const isActive = z.boolean({
required_error: "isActive is required",
invalid_type_error: "isActive must be a boolean",
});
日期
使用 z.date() 验证 Date
实例。
z.date().safeParse(new Date()); // success: true
z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false
您可以在创建日期架构时自定义某些错误消息。
const myDateSchema = z.date({
required_error: "Please select a date and time",
invalid_type_error: "That's not a date!",
});
Zod 提供了一些特定于日期的验证。
z.date().min(new Date("1900-01-01"), { message: "Too old" });
z.date().max(new Date(), { message: "Too young!" });
支持日期字符串
要编写接受Date
或日期字符串的架构,请使用z.preprocess
。
const dateSchema = z.preprocess((arg) => {
if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
}, z.date());
type DateSchema = z.infer<typeof dateSchema>;
// type DateSchema = Date
dateSchema.safeParse(new Date("1/12/22")); // success: true
dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true
Zod enums
const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
type FishEnum = z.infer<typeof FishEnum>;
// 'Salmon' | 'Tuna' | 'Trout'
z.enum
是一种 Zod 原生方法,用于声明具有一组固定的允许字符串值的模式。将值数组直接传递到 z.enum()
中。或者,使用 as const
将枚举值定义为字符串元组。有关详细信息,请参阅 const 断言文档。
const VALUES = ["Salmon", "Tuna", "Trout"] as const;
const FishEnum = z.enum(VALUES);
这是不允许的,因为 Zod 无法推断每个元素的确切值。
const fish = ["Salmon", "Tuna", "Trout"];
const FishEnum = z.enum(fish);
自动完成
要使用 Zod 枚举实现自动完成,请使用架构的 .enum
属性:
FishEnum.enum.Salmon; // => autocompletes
FishEnum.enum;
/*
=> {
Salmon: "Salmon",
Tuna: "Tuna",
Trout: "Trout",
}
*/
您还可以使用 .options 将选项列表作为元组检索
属性:
FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
本机枚举
Zod 枚举是定义和验证枚举的推荐方法。但是,如果您需要针对第三方库中的枚举进行验证(或者您不想重写现有枚举),则可以使用 z.nativeEnum()
。
数字枚举
enum Fruits {
Apple,
Banana,
}
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Banana); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse(1); // passes
FruitEnum.parse(3); // fails
字符串枚举
enum Fruits {
Apple = "apple",
Banana = "banana",
Cantaloupe, // you can mix numerical and string enums
}
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Cantaloupe); // passes
FruitEnum.parse("apple"); // passes
FruitEnum.parse("banana"); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse("Cantaloupe"); // fails
常量枚举
.nativeEnum()
函数适用于as const
对象也是如此。 ⚠️ as const
需要 TypeScript 3.4+!
const Fruits = {
Apple: "apple",
Banana: "banana",
Cantaloupe: 3,
} as const;
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3
FruitEnum.parse("apple"); // passes
FruitEnum.parse("banana"); // passes
FruitEnum.parse(3); // passes
FruitEnum.parse("Cantaloupe"); // fails
您可以使用 .enum
属性访问底层对象:
FruitEnum.enum.Apple; // "apple"
可选
您可以使用 z.Optional()
使任何模式可选。这会将架构包装在 ZodOptional
实例中并返回结果。
const schema = z.optional(z.string());
schema.parse(undefined); // => returns undefined
type A = z.infer<typeof schema>; // string | undefined
为了方便起见,您还可以在现有架构上调用 .optional()
方法。
const user = z.object({
username: z.string().optional(),
});
type C = z.infer<typeof user>; // { username?: string | undefined };
您可以使用 .unwrap()
从 ZodOptional
实例中提取包装的架构。
const stringSchema = z.string();
const optionalString = stringSchema.optional();
optionalString.unwrap() === stringSchema; // true
类似地
,您可以使用 z.nullable()
创建可为 null 的类型。
const nullableString = z.nullable(z.string());
nullableString.parse("asdf"); // => "asdf"
nullableString.parse(null); // => null
或者使用 .nullable()
方法。
const E = z.string().nullable(); // equivalent to nullableString
type E = z.infer<typeof E>; // string | null
使用 .unwrap()
提取内部架构。
const stringSchema = z.string();
const nullableString = stringSchema.nullable();
nullableString.unwrap() === stringSchema; // true
对象
// all properties are required by default
const Dog = z.object({
name: z.string(),
age: z.number(),
});
// extract the inferred type like this
type Dog = z.infer<typeof Dog>;
// equivalent to:
type Dog = {
name: string;
age: number;
};
.shape
使用 .shape
访问特定键的架构。
Dog.shape.name; // => string schema
Dog.shape.age; // => number schema
.keyof
使用 .keyof
从对象模式的键创建 ZodEnum
模式。
const keySchema = Dog.keyof();
keySchema; // ZodEnum<["name", "age"]>
.extend
您可以使用 .extend
方法向对象模式添加其他字段。
const DogWithBreed = Dog.extend({
breed: z.string(),
});
您可以使用.extend
来覆盖字段!小心这个力量!
.merge
相当于A.extend(B.shape)
。
const BaseTeacher = z.object({ students: z.array(z.string()) });
const HasID = z.object({ id: z.string() });
const Teacher = BaseTeacher.merge(HasID);
type Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string }
如果两个模式共享密钥,则 B 的属性将覆盖 A 的属性。返回的模式还会继承“unknownKeys”策略(strip/strict/passthrough)和 B 的包罗万象的模式。
.pick/.omit< /code>
受 TypeScript 内置 Pick
和 Omit
实用程序类型的启发,所有 Zod 对象架构都具有 .pick
和 .omit< /code> 返回修改版本的方法。考虑这个配方模式:
const Recipe = z.object({
id: z.string(),
name: z.string(),
ingredients: z.array(z.string()),
});
要仅保留某些键,请使用 .pick
。
const JustTheName = Recipe.pick({ name: true });
type JustTheName = z.infer<typeof JustTheName>;
// => { name: string }
要删除某些键,请使用 .omit
。
const NoIDRecipe = Recipe.omit({ id: true });
type NoIDRecipe = z.infer<typeof NoIDRecipe>;
// => { name: string, ingredients: string[] }
.partial
受到内置 TypeScript 实用程序类型的启发 Partial,.partial
方法使所有属性都是可选的。
从这个对象开始:
const user = z.object({
email: z.string()
username: z.string(),
});
// { email: string; username: string }
我们可以创建一个部分版本:
const partialUser = user.partial();
// { email?: string | undefined; username?: string | undefined }
您还可以指定哪些属性为可选:
const optionalEmail = user.partial({
email: true,
});
/*
{
email?: string | undefined;
username: string
}
*/
.deepPartial
.partial
方法是浅层的 - 它只适用于一个级别深的。还有一个“深度”版本:
const user = z.object({
username: z.string(),
location: z.object({
latitude: z.number(),
longitude: z.number(),
}),
strings: z.array(z.object({ value: z.string() })),
});
const deepPartialUser = user.deepPartial();
/*
{
username?: string | undefined,
location?: {
latitude?: number | undefined;
longitude?: number | undefined;
} | undefined,
strings?: { value?: string}[]
}
*/
重要限制:深度部分只能在对象、数组和元组的层次结构中按预期工作。
.required
与 .partial
方法相反,.required
方法使所有属性成为必需。
从这个对象开始:
const user = z.object({
email: z.string()
username: z.string(),
}).partial();
// { email?: string | undefined; username?: string | undefined }
我们可以创建一个所需的版本:
const requiredUser = user.required();
// { email: string; username: string }
您还可以指定哪些属性是必需的:
const requiredEmail = user.required({
email: true,
});
/*
{
email: string;
username?: string | undefined;
}
*/
.passthrough
默认情况下,Zod 对象模式会在解析过程中剔除无法识别的键。
const person = z.object({
name: z.string(),
});
person.parse({
name: "bob dylan",
extraKey: 61,
});
// => { name: "bob dylan" }
// extraKey has been stripped
相反,如果您想传递未知密钥,请使用 .passthrough()
。
person.passthrough().parse({
name: "bob dylan",
extraKey: 61,
});
// => { name: "bob dylan", extraKey: 61 }
.strict
默认情况下,Zod 对象架构会在解析过程中剔除无法识别的键。您可以使用 .strict()
禁止未知键。如果输入中有任何未知的键,Zod 将抛出错误。
const person = z
.object({
name: z.string(),
})
.strict();
person.parse({
name: "bob dylan",
extraKey: 61,
});
// => throws ZodError
.strip
您可以使用 .strip
方法将对象模式重置为默认行为(剥离无法识别的键)。
.catchall
您可以将“catchall”模式传递到对象模式中。所有未知的密钥都将根据它进行验证。
const person = z
.object({
name: z.string(),
})
.catchall(z.number());
person.parse({
name: "bob dylan",
validExtraKey: 61, // works fine
});
person.parse({
name: "bob dylan",
validExtraKey: false, // fails
});
// => throws ZodError
使用 .catchall()
可以避免 .passthrough()
、 .strip()
或 .strict()
。所有密钥现在都被视为“已知”。
数组
const stringArray = z.array(z.string());
// equivalent
const stringArray = z.string().array();
请小心使用 .array()
方法。它返回一个新的 ZodArray
实例。这意味着调用方法的顺序很重要。例如:
z.string().optional().array(); // (string | undefined)[]
z.string().array().optional(); // string[] | undefined
.element
使用 .element
访问数组元素的架构。
stringArray.element; // => string schema
.nonempty
如果要确保数组至少包含一个元素,请使用 .nonempty()
。
const nonEmptyStrings = z.string().array().nonempty();
// the inferred type is now
// [string, ...string[]]
nonEmptyStrings.parse([]); // throws: "Array cannot be empty"
nonEmptyStrings.parse(["Ariana Grande"]); // passes
您可以选择指定自定义错误消息:
// optional custom error message
const nonEmptyStrings = z.string().array().nonempty({
message: "Can't be empty!",
});
.min/.max/.length
z.string().array().min(5); // must contain 5 or more items
z.string().array().max(5); // must contain 5 or fewer items
z.string().array().length(5); // must contain 5 items exactly
与.nonempty()
不同,这些方法不会更改推断的类型。
元组
与数组不同,元组具有固定数量的元素,并且每个元素可以具有不同的类型。
const athleteSchema = z.tuple([
z.string(), // name
z.number(), // jersey number
z.object({
pointsScored: z.number(),
}), // statistics
]);
type Athlete = z.infer<typeof athleteSchema>;
// type Athlete = [string, number, { pointsScored: number }]
可以使用 .rest
方法添加可变参数(“rest”)。
const variadicTuple = z.tuple([z.string()]).rest(z.number());
const result = variadicTuple.parse(["hello", 1, 2, 3]);
// => [string, ...number[]];
Unions
Zod 包含一个用于组合“OR”类型的内置 z.union
方法。
const stringOrNumber = z.union([z.string(), z.number()]);
stringOrNumber.parse("foo"); // passes
stringOrNumber.parse(14); // passes
Zod 将按顺序测试每个“选项”的输入,并返回第一个成功验证的值。
为了方便起见,您还可以使用 .or
方法:
const stringOrNumber = z.string().or(z.number());
区分联合
区分联合是所有共享特定键的对象模式的联合。
type MyUnion =
| { status: "success"; data: string }
| { status: "failed"; error: Error };
此类联合可以用 z.discriminatedUnion 方法表示。这可以实现更快的评估,因为 Zod 可以检查鉴别器键(上例中的状态)以确定应使用哪个模式来解析输入。这使得解析更加高效,并让 Zod 提供更友好的错误报告。
使用基本联合方法,输入会根据提供的每个“选项”进行测试,如果无效,所有“选项”的问题都会显示在 zod 错误中。另一方面,受歧视的联合允许仅选择一个“选项”,对其进行测试,并仅显示与该“选项”相关的问题。
const myUnion = z.discriminatedUnion("status", [
z.object({ status: z.literal("success"), data: z.string() }),
z.object({ status: z.literal("failed"), error: z.instanceof(Error) }),
]);
myUnion.parse({ type: "success", data: "yippie ki yay" });
记录
记录模式用于验证诸如 { [k: string]: number }
之类的类型。
如果您想根据某些模式验证对象的值,但不关心键,请使用z.record(valueType)
:
const NumberCache = z.record(z.number());
type NumberCache = z.infer<typeof NumberCache>;
// => { [k: string]: number }
这对于存储特别有用或按 ID 缓存项目。
const userStore: UserStore = {};
userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
name: "Carlotta",
}; // passes
userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
whatever: "Ice cream sundae",
}; // TypeError
记录键类型
如果您想同时验证键和值,请使用
z.record(keyType, valueType)
:
const NoEmptyKeysSchema = z.record(z.string().min(1), z.number());
NoEmptyKeysSchema.parse({ count: 1 }); // => { 'count': 1 }
NoEmptyKeysSchema.parse({ "": 1 }); // fails
(注意传递两个参数时,valueType
是第二个参数)
关于数字键
而 z.record(keyType, valueType)
能够接受数字键类型,而 TypeScript 的内置 Record 类型是 Record
,在 Zod 中很难表示 TypeScript 类型 Record
。
事实证明,TypeScript 围绕 [k: number]
的行为有点不直观:
const testMap: { [k: number]: string } = {
1: "one",
};
for (const key in testMap) {
console.log(`${key}: ${typeof key}`);
}
// prints: `1: string`
如您所见,JavaScript 在幕后自动将所有对象键转换为字符串。由于 Zod 试图弥合静态类型和运行时类型之间的差距,因此提供一种使用数字键创建记录模式的方法是没有意义的,因为运行时 JavaScript 中不存在数字键这样的东西。
地图集
const stringNumberMap = z.map(z.string(), z.number());
type StringNumberMap = z.infer<typeof stringNumberMap>;
// type StringNumberMap = Map<string, number>
地图集
const numberSet = z.set(z.number());
type NumberSet = z.infer<typeof numberSet>;
// type NumberSet = Set<number>
可以使用以下实用方法进一步限制
z.set(z.string()).nonempty(); // must contain at least one item
z.set(z.string()).min(5); // must contain 5 or more items
z.set(z.string()).max(5); // must contain 5 or fewer items
z.set(z.string()).size(5); // must contain 5 items exactly
集模式。交点
交点对于创建“逻辑 AND”类型非常有用。这对于相交两个对象类型非常有用。
const Person = z.object({
name: z.string(),
});
const Employee = z.object({
role: z.string(),
});
const EmployedPerson = z.intersection(Person, Employee);
// equivalent to:
const EmployedPerson = Person.and(Employee);
尽管在许多情况下,建议使用 A.merge(B)
来合并两个对象。 .merge
方法返回一个新的 ZodObject
实例,而 A.and(B)
返回一个不太有用的 ZodIntersection
缺少常见对象方法(例如 pick
和 omit
)的实例。
const a = z.union([z.number(), z.string()]);
const b = z.union([z.number(), z.boolean()]);
const c = z.intersection(a, b);
type c = z.infer<typeof c>; // => number
递归类型
您可以在 Zod 中定义递归模式,但由于 TypeScript 的限制,无法静态推断它们的类型。相反,您需要手动定义类型定义,并将其作为“类型提示”提供给 Zod。
interface Category {
name: string;
subcategories: Category[];
}
// cast to z.ZodType<Category>
const Category: z.ZodType<Category> = z.lazy(() =>
z.object({
name: z.string(),
subcategories: z.array(Category),
})
);
Category.parse({
name: "People",
subcategories: [
{
name: "Politicians",
subcategories: [{ name: "Presidents", subcategories: [] }],
},
],
}); // passes
不幸的是,这段代码有点重复,因为您声明了两次类型:一次在接口中,另一次在 Zod 定义中。
JSON 类型
如果您想验证任何 JSON 值,可以使用下面的代码片段。
const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
type Literal = z.infer<typeof literalSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const jsonSchema: z.ZodType<Json> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
);
jsonSchema.parse(data);
感谢 ggoodman 的建议。
循环对象
尽管支持递归模式,但将循环数据传递到 Zod 中将导致无限循环。
承诺
const numberPromise = z.promise(z.number());
“解析”的工作方式与承诺模式略有不同。验证分两部分进行:
- Zod 同步检查输入是否是 Promise 的实例(即具有
.then
和 .catch
方法的对象。)。
- Zod 使用
.then
将额外的验证步骤附加到现有的 Promise 上。您必须对返回的 Promise 使用 .catch
来处理验证失败。
numberPromise.parse("tuna");
// ZodError: Non-Promise type: string
numberPromise.parse(Promise.resolve("tuna"));
// => Promise<number>
const test = async () => {
await numberPromise.parse(Promise.resolve("tuna"));
// ZodError: Non-number type: string
await numberPromise.parse(Promise.resolve(3.14));
// => 3.14
};
Instanceof
您可以使用 z.instanceof
来检查输入是否是类的实例。这对于验证从第三方库导出的类的输入非常有用。
class Test {
name: string;
}
const TestSchema = z.instanceof(Test);
const blob: any = "whatever";
TestSchema.parse(new Test()); // passes
TestSchema.parse("blob"); // throws
函数模式
Zod 还允许您定义“函数模式”。这使得验证函数的输入和输出变得很容易,而无需混合验证代码和“业务逻辑”。
您可以使用 z.function(args, returnType)
创建函数架构。
const myFunction = z.function();
type myFunction = z.infer<typeof myFunction>;
// => ()=>unknown
定义输入和输出。
const myFunction = z
.function()
.args(z.string(), z.number()) // accepts an arbitrary number of arguments
.returns(z.boolean());
type myFunction = z.infer<typeof myFunction>;
// => (arg0: string, arg1: number)=>boolean
函数模式有一个 .implement()
方法,该方法接受一个函数并返回一个自动验证其输入和输出的新函数。
const trimmedLength = z
.function()
.args(z.string()) // accepts an arbitrary number of arguments
.returns(z.number())
.implement((x) => {
// TypeScript knows x is a string!
return x.trim().length;
});
trimmedLength("sandwich"); // => 8
trimmedLength(" asdf "); // => 4
如果您只关心验证输入,则不要调用 .returns()
方法。输出类型将从实现中推断出来。
如果您的函数不返回任何内容,您可以使用特殊的 z.void()
选项。这将使 Zod 正确推断 void 返回函数的类型。 (返回空值的函数实际上返回未定义。)
const myFunction = z
.function()
.args(z.string())
.implement((arg) => {
return [arg.length]; //
});
myFunction; // (arg: string)=>number[]
从函数模式中提取输入和输出模式。
myFunction.parameters();
// => ZodTuple<[ZodString, ZodNumber]>
myFunction.returnType();
// => ZodBoolean
预处理
Zod 通常在“解析然后转换”范例下运行。 Zod 首先验证输入,然后将其传递给一系列转换函数。 (有关转换的更多信息,请阅读 .transform 文档。)
但有时您希望在解析发生之前对输入应用一些转换。一个常见的用例:类型强制。 Zod 通过 z.preprocess()
启用此功能。
const castToString = z.preprocess((val) => String(val), z.string());
这将返回一个 ZodEffects
实例。 ZodEffects 是一个包装类,其中包含与预处理、细化和转换相关的所有逻辑。
模式方法
所有 Zod 模式都包含某些方法。
.parse
.parse(data:known): T
给定任何 Zod 模式,您可以调用其 .parse
方法来检查 data
有效。如果是,则返回一个带有完整类型信息的值!否则,会抛出错误。
重要提示:.parse
返回的值是您传入的变量的深度克隆。
const stringSchema = z.string();
stringSchema.parse("fish"); // => returns "fish"
stringSchema.parse(12); // throws Error('Non-string type: number');
.parseAsync
.parseAsync(data:未知):Promise
如果您使用异步细化或转换(稍后会详细介绍) ,您需要使用 .parseAsync
const stringSchema1 = z.string().refine(async (val) => val.length < 20);
const value1 = await stringSchema.parseAsync("hello"); // => hello
const stringSchema2 = z.string().refine(async (val) => val.length > 20);
const value2 = await stringSchema.parseAsync("hello"); // => throws
.safeParse
.safeParse(data:unknown): { success: true; }数据:T; } | { 成功:假;错误:ZodError; }
如果您不希望 Zod 在验证失败时抛出错误,请使用 .safeParse
。此方法返回一个对象,其中包含成功解析的数据或包含有关验证问题的详细信息的 ZodError 实例。
stringSchema.safeParse(12);
// => { success: false; error: ZodError }
stringSchema.safeParse("billie");
// => { success: true; data: 'billie' }
结果是一个可区分的联合,因此您可以非常方便地处理错误:
const result = stringSchema.safeParse("billie");
if (!result.success) {
// handle error then return
result.error;
} else {
// do something
result.data;
}
.safeParseAsync
别名:.spa
safeParse
的异步版本。
await stringSchema.safeParseAsync("billie");
为了方便起见,它被别名为 .spa
:
await stringSchema.spa("billie");
.refine
.refine(validator: (data:T)=>any, params?: RefineParams)
Zod 允许您通过细化提供自定义验证逻辑。 (有关创建多个问题和自定义错误代码等高级功能,请参阅 .superRefine
。)
Zod 旨在尽可能地反映 TypeScript。但是,您可能希望检查许多所谓的“细化类型”,它们是否无法在 TypeScript 的类型系统中表示。例如:检查数字是否为整数或字符串是否为有效的电子邮件地址。
例如,您可以使用 .refine
对任何 Zod 模式定义自定义验证检查:
const myString = z.string().refine((val) => val.length <= 255, {
message: "String can't be more than 255 characters",
});
⚠️ 细化函数不应抛出异常。相反,他们应该返回一个错误值来表示失败。
。
如您所见,。refine
进行两个参数
- 第一个是验证功能。此功能采用一个输入(类型
t
- 架构的推断类型),并返回任何
。任何真实价值都将通过验证。 (在zod@1.6.2之前,验证功能必须返回布尔值。)
- 第二个参数接受了一些选项。您可以使用它来自定义某些错误处理行为:
type RefineParams = {
// override error message
message?: string;
// appended to error path
path?: (string | number)[];
// params object you can use to customize message
// in error map
params?: object;
};
的函数,
z.string().refine(
(val) => val.length > 10,
(val) => ({ message: `${val} is not more than 10 characters` })
);
对于高级案例,第二个参数也可以是返回 RefineParams
/自定义错误路径
const passwordForm = z
.object({
password: z.string(),
confirm: z.string(),
})
.refine((data) => data.password === data.confirm, {
message: "Passwords don't match",
path: ["confirm"], // path of error
})
.parse({ password: "asdf", confirm: "qwer" });
因为您提供了 PATH> PATH
参数,结果误差将是:
ZodError {
issues: [{
"code": "custom",
"path": [ "confirm" ],
"message": "Passwords don't match"
}]
}
异步细化的
细化也可以是异步:
const userId = z.string().refine(async (id) => {
// verify that ID exists in database
return true;
});
⚠️如果您使用异步改进,则必须使用 .parseasync
方法来解析数据!否则ZOD会丢下错误。
可以交错:
z.string()
.transform((val) => val.length)
.refine((val) => val > 25);
.superrefine
.refine
方法实际上是一种更广泛的(和verbose)方法,称为 superrefine
代码>.这是一个示例:
const Strings = z.array(z.string()).superRefine((val, ctx) => {
if (val.length > 3) {
ctx.addIssue({
code: z.ZodIssueCode.too_big,
maximum: 3,
type: "array",
inclusive: true,
message: "Too many items ????",
});
}
if (val.length !== new Set(val).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `No duplicates allowed.`,
});
}
});
您可以根据需要添加尽可能多的问题。如果 ctx.addissue
是 在函数执行过程中,请通过验证。
通常,改进始终可以使用 Zodissuecode.custom
错误代码创建问题,但是使用超级fine
您可以创建任何代码的任何问题。每个问题代码在错误处理指南中详细描述: error_handling.md 。
默认情况
下,即使在改进支票失败后,解析仍将继续。例如,如果您将多个修补链链在一起,则将全部执行。但是,可能需要早期中止以防止后来的细化被执行。要实现这一目标,请将致命
标志传递给 ctx.addissue
,然后返回 z.never
。
const schema = z.number().superRefine((val, ctx) => {
if (val < 10) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "should be >= 10",
fatal: true,
});
return z.NEVER;
}
if (val !== 12) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "should be twelve",
});
}
});
在解析后转换数据,使用 transform
方法。
const stringToNumber = z.string().transform((val) => val.length);
stringToNumber.parse("string"); // => 6
链顺序
请注意, stringtonumber
是 Zodeffects
子类的实例。它不是 Zodstring
的实例。如果要使用 zodstring
的内置方法(例如 .email()),则必须在任何变换之前应用这些方法。
const emailToDomain = z
.string()
.email()
.transform((val) => val.split("@")[1]);
emailToDomain.parse("colinhacks@example.com"); // => example.com
.transform
方法可以同时验证和转换值。这通常比链接
和 validate
更简单且重复。
与 .superrefine
一样,转换函数使用 ctx
对象使用 addissue
方法,可用于注册验证问题。
const Strings = z.string().transform((val, ctx) => {
const parsed = parseInt(val);
if (isNaN(parsed)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Not a number",
});
// This is a special symbol you can use to
// return early from the transform function.
// It has type `never` so it does not affect the
// inferred return type.
return z.NEVER;
}
return parsed;
});
与改进的关系
转换和改进可以交错。这些将按声明的顺序执行。
z.string()
.transform((val) => val.toUpperCase())
.refine((val) => val.length > 15)
.transform((val) => `Hello ${val}`)
.refine((val) => val.indexOf("!") === -1);
变换也可以是异步。
const IdToUser = z
.string()
.uuid()
.transform(async (id) => {
return await getUserById(id);
});
⚠️如果您的模式包含异步变换,则必须使用.parseasync()或.safeparseasync()来解析数据。否则ZOD会丢下错误。
.default
您可以使用变换来在ZOD中实现“默认值”的概念。
const stringWithDefault = z.string().default("tuna");
stringWithDefault.parse(undefined); // => "tuna"
可选地,您可以将函数传递到 .default
时,每当需要生成默认值时,该函数将被重新执行:
const numberWithRandomDefault = z.number().default(Math.random);
numberWithRandomDefault.parse(undefined); // => 0.4413456736055323
numberWithRandomDefault.parse(undefined); // => 0.1871840107401901
numberWithRandomDefault.parse(undefined); // => 0.7223408162401552
从概念上讲,这就是zod流程默认值的方式:
- 如果输入为
Undefined
,默认值将返回,
- 否则,数据将使用基本架构
.catch
使用使用 .catch()
提供“捕获值”如果发生解析错误,返回。
const numberWithCatch = z.number().catch(42);
numberWithCatch.parse(5); // => 5
numberWithCatch.parse("tuna"); // => 42
可选地,您可以将函数传递到 .catch
时,每当需要生成默认值时,该函数将被重新执行:
const numberWithRandomCatch = z.number().catch(Math.random);
numberWithRandomDefault.parse("sup"); // => 0.4413456736055323
numberWithRandomDefault.parse("sup"); // => 0.1871840107401901
numberWithRandomDefault.parse("sup"); // => 0.7223408162401552
从概念上讲,这就是zod进程“捕获值”的方式:
- 使用使用该数据来解析数据基本架构
- 如果解析失败,则返回“捕获值”
.ptional
便利方法返回架构的可选版本。
const optionalString = z.string().optional(); // string | undefined
// equivalent to
z.optional(z.string());
.nullable
一种便利方法返回架构的无效版本。
const nullableString = z.string().nullable(); // string | null
// equivalent to
z.nullable(z.string());
.Nullish
一种便利方法,它返回架构的“无效”版本。无效的模式将同时接受未定义的
和 null
。阅读有关“无效的”概念笔记。
const nullishString = z.string().nullish(); // string | null | undefined
// equivalent to
z.string().optional().nullable();
.array
一种便利方法,它返回给定类型的数组模式:
const nullableString = z.string().array(); // string[]
// equivalent to
z.array(z.string());
.promise
Promise类型的便利方法:
const stringPromise = z.string().promise(); // Promise<string>
// equivalent to
z.promise(z.string());
.or
便利方法用于工会类型。
z.string().or(z.number()); // string | number
// equivalent to
z.union([z.string(), z.number()]);
。和
一种用于创建相交类型的便利方法。
z.object({ name: z.string() }).and(z.object({ age: z.number() })); // { name: string } & { age: number }
// equivalent to
z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));
.brand
.brand&lt; t&gt;()=&gt; Zodbranded&lt; this,B&gt;
打字条类型系统是结构性的,这意味着在结构上等效的任何两种类型都被认为是相同的。
type Cat = { name: string };
type Dog = { name: string };
const petCat = (cat: Cat) => {};
const fido: Dog = { name: "fido" };
petCat(fido); // works fine
在某些情况下,可以在打字稿内模拟标称键入标称键入。例如,您可能希望编写一个仅接受ZOD验证的输入的函数。这可以通过品牌类型(aka 不透明类型)来实现。
const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;
const petCat = (cat: Cat) => {};
// this works
const simba = Cat.parse({ name: "simba" });
petCat(simba);
// this doesn't
petCat({ name: "fido" });
在引擎盖下,这是通过使用相交类型将“品牌”附加到推理类型上的作用。这样,普通/未品牌的数据结构不再可分配给架构的推断类型。
const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;
// {name: string} & {[symbol]: "Cat"}
请注意,品牌类型不会影响 .parse
的运行时结果。这是一个仅静态构造。
指南和概念
类型推理
您可以使用 Z.Infer&lt; type Myschema&gt;
提取任何模式的打字稿类型。
const A = z.string();
type A = z.infer<typeof A>; // string
const u: A = 12; // TypeError
const u: A = "asdf"; // compiles
变换呢?
实际上每个ZOD模式在内部跟踪两种类型:输入和输出。对于大多数模式(例如 z.String()
)这两个是相同的。但是,一旦添加到混合物中,这两个值就会差异。实例 z.String()。transform(val =&gt; val.length)
具有 String
的输入和 numbern
的输出。
您可以单独提取输入和输出类型这样的类型:
const stringToNumber = z.string().transform((val) => val.length);
// ⚠️ Important: z.infer returns the OUTPUT type!
type input = z.input<typeof stringToNumber>; // string
type output = z.output<typeof stringToNumber>; // number
// equivalent to z.output!
type inferred = z.infer<typeof stringToNumber>; // number
在尝试编写接受ZOD模式作为输入的函数时编写通用功能
,尝试这样的事情是很常见的:
function makeSchemaOptional<T>(schema: z.ZodType<T>) {
return schema.optional();
}
此方法有一些问题。此功能中的架构
变量将作为 Zodtype
的实例,这是所有Zod schemas saraxtion的抽象类。这种方法失去类型信息,即输入实际是哪个子类。
const arg = makeSchemaOptional(z.string());
arg.unwrap();
一种更好的方法是生成参数,指 整体。
function makeSchemaOptional<T extends z.ZodTypeAny>(schema: T) {
return schema.optional();
}
zodtypeany
只是 zodtype&lt; any,any,任何&gt;
的速记,一种足够宽的类型,足以匹配任何Zod架构。
如您所见, schema
现在已完全且正确地键入。
const arg = makeSchemaOptional(z.string());
arg.unwrap(); // ZodString
zodtype
类具有三个通用参数。
class ZodType<
Output = any,
Def extends ZodTypeDef = ZodTypeDef,
Input = Output
> { ... }
通过将这些限制在通用输入中,您可以限制允许的模式作为函数的输入:
function makeSchemaOptional<T extends z.ZodType<string>>(schema: T) {
return schema.optional();
}
makeSchemaOptional(z.string());
// works fine
makeSchemaOptional(z.number());
// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>'
错误处理
ZOD提供了一个错误的子类,称为 Zoderror
。 Zoderrors包含问题
数组,其中包含有关验证问题的详细信息。
const data = z
.object({
name: z.string(),
})
.safeParse({ name: 12 });
if (!data.success) {
data.error.issues;
/* [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [ "name" ],
"message": "Expected string, received number"
}
] */
}
有关可能的错误代码以及如何自定义错误消息的详细信息,请查看专用错误处理指南: error_handling.md.md
zod的错误报告强调完整性完整性和正确性。如果您想向最终用户提供有用的错误消息,则应使用错误映射覆盖ZOD的错误消息(在错误处理指南中详细描述)或使用第三方库,例如 zod-validation-error
您可以使用 .format().format()
方法到将此错误转换为嵌套对象。
const data = z
.object({
name: z.string(),
})
.safeParse({ name: 12 });
if (!data.success) {
const formatted = data.error.format();
/* {
name: { _errors: [ 'Expected string, received number' ] }
} */
formatted.name?._errors;
// => ["Expected string, received number"]
}
比较
还有少数其他广泛使用的验证库,但是所有这些库都有某些设计限制,从而构成了非理想的开发人员体验。
&lt;! - |特色| zod | joi | yup | io-ts | [runtypes](https://github.com/pelo
Zod
✨ https://zod.dev ✨
TypeScript-first schema validation with static type inference
These docs have been translated into Chinese.
Table of contents
Introduction
Zod is a TypeScript-first schema declaration and validation library. I'm using the term "schema" to broadly refer to any data type, from a simple string
to a complex nested object.
Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It's easy to compose simpler types into complex data structures.
Some other great aspects:
- Zero dependencies
- Works in Node.js and all modern browsers
- Tiny: 8kb minified + zipped
- Immutable: methods (i.e.
.optional()
) return a new instance
- Concise, chainable interface
- Functional approach: parse, don't validate
- Works with plain JavaScript too! You don't need to use TypeScript.
Sponsorship at any level is appreciated and encouraged. For individual developers, consider the Cup of Coffee tier. If you built a paid product using Zod, consider one of the podium tiers.
Gold
Silver
Bronze
Ecosystem
There are a growing number of tools that are built atop or support Zod natively! If you've built a tool or library on top of Zod, tell me about it on Twitter or start a Discussion. I'll add it below and tweet it out.
Resources
API libraries
tRPC
: Build end-to-end typesafe APIs without GraphQL.
@anatine/zod-nestjs
: Helper methods for using Zod in a NestJS project.
zod-endpoints
: Contract-first strictly typed endpoints with Zod. OpenAPI compatible.
domain-functions
: Decouple your business logic from your framework using composable functions. With first-class type inference from end to end powered by Zod schemas.
@zodios/core
: A typescript API client with runtime and compile time validation backed by axios and zod.
express-zod-api
: Build Express-based APIs with I/O schema validation and custom middlewares.
react-hook-form
: A first-party Zod resolver for React Hook Form.
zod-validation-error
: Generate user-friendly error messages from ZodError
s
zod-formik-adapter
: A community-maintained Formik adapter for Zod.
react-zorm
: Standalone <form>
generation and validation for React using Zod.
zodix
: Zod utilities for FormData and URLSearchParams in Remix loaders and actions.
Zod to X
X to Zod
Mocking
Powered by Zod
slonik
: Node.js Postgres client with strong Zod integration.
soly
: Create CLI applications with zod.
zod-xlsx
: A xlsx based resource validator using Zod schemas.
Installation
Requirements
- TypeScript 4.1+!
- You must enable
strict
mode in your tsconfig.json
. This is a best practice for all TypeScript projects.
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}
From npm
(Node/Bun)
npm install zod # npm
yarn add zod # yarn
bun add zod # bun
pnpm add zod # pnpm
From deno.land/x
(Deno)
Unlike Node, Deno relies on direct URL imports instead of a package manager like NPM. Zod is available on deno.land/x. The latest version can be imported like so:
import { z } from "https://deno.land/x/zod/mod.ts";
You can also specify a particular version:
import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts";
The rest of this README assumes you are using npm and importing directly from the "zod"
package.
Basic usage
Creating a simple string schema
import { z } from "zod";
// creating a schema for strings
const mySchema = z.string();
// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError
// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }
Creating an object schema
import { z } from "zod";
const User = z.object({
username: z.string(),
});
User.parse({ username: "Ludwig" });
// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }
Primitives
import { z } from "zod";
// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();
// empty types
z.undefined();
z.null();
z.void(); // accepts undefined
// catch-all types
// allows any value
z.any();
z.unknown();
// never type
// allows no values
z.never();
Literals
const tuna = z.literal("tuna");
const twelve = z.literal(12);
const twobig = z.literal(2n); // bigint literal
const tru = z.literal(true);
const terrificSymbol = Symbol("terrific");
const terrific = z.literal(terrificSymbol);
// retrieve literal value
tuna.value; // "tuna"
Currently there is no support for Date literals in Zod. If you have a use case for this feature, please file an issue.
Strings
Zod includes a handful of string-specific validations.
z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().email();
z.string().url();
z.string().uuid();
z.string().cuid();
z.string().regex(regex);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().trim(); // trim whitespace
z.string().datetime(); // defaults to UTC, see below for options
Check out validator.js for a bunch of other useful string validation functions that can be used in conjunction with Refinements.
You can customize some common error messages when creating a string schema.
const name = z.string({
required_error: "Name is required",
invalid_type_error: "Name must be a string",
});
When using validation methods, you can pass in an additional argument to provide a custom error message.
z.string().min(5, { message: "Must be 5 or more characters long" });
z.string().max(5, { message: "Must be 5 or fewer characters long" });
z.string().length(5, { message: "Must be exactly 5 characters long" });
z.string().email({ message: "Invalid email address" });
z.string().url({ message: "Invalid url" });
z.string().uuid({ message: "Invalid UUID" });
z.string().startsWith("https://", { message: "Must provide secure URL" });
z.string().endsWith(".com", { message: "Only .com domains allowed" });
z.string().datetime({ message: "Invalid datetime string! Must be UTC." });
Datetime validation
The z.string().datetime()
method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision.
const datetime = z.string().datetime();
datetime.parse("2020-01-01T00:00:00Z"); // pass
datetime.parse("2020-01-01T00:00:00.123Z"); // pass
datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision)
datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed)
Timezone offsets can be allowed by setting the offset
option to true
.
const datetime = z.string().datetime({ offset: true });
datetime.parse("2020-01-01T00:00:00+02:00"); // pass
datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional)
datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported)
You can additionally constrain the allowable precision
. By default, arbitrary sub-second precision is supported (but optional).
const datetime = z.string().datetime({ precision: 3 });
datetime.parse("2020-01-01T00:00:00.123Z"); // pass
datetime.parse("2020-01-01T00:00:00Z"); // fail
datetime.parse("2020-01-01T00:00:00.123456Z"); // fail
Numbers
You can customize certain error messages when creating a number schema.
const age = z.number({
required_error: "Age is required",
invalid_type_error: "Age must be a number",
});
Zod includes a handful of number-specific validations.
z.number().gt(5);
z.number().gte(5); // alias .min(5)
z.number().lt(5);
z.number().lte(5); // alias .max(5)
z.number().int(); // value must be an integer
z.number().positive(); // > 0
z.number().nonnegative(); // >= 0
z.number().negative(); // < 0
z.number().nonpositive(); // <= 0
z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5)
z.number().finite(); // value must be finite, not Infinity or -Infinity
Optionally, you can pass in a second argument to provide a custom error message.
z.number().lte(5, { message: "this????is????too????big" });
NaNs
You can customize certain error messages when creating a nan schema.
const isNaN = z.nan({
required_error: "isNaN is required",
invalid_type_error: "isNaN must be not a number",
});
Booleans
You can customize certain error messages when creating a boolean schema.
const isActive = z.boolean({
required_error: "isActive is required",
invalid_type_error: "isActive must be a boolean",
});
Dates
Use z.date() to validate Date
instances.
z.date().safeParse(new Date()); // success: true
z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false
You can customize certain error messages when creating a date schema.
const myDateSchema = z.date({
required_error: "Please select a date and time",
invalid_type_error: "That's not a date!",
});
Zod provides a handful of date-specific validations.
z.date().min(new Date("1900-01-01"), { message: "Too old" });
z.date().max(new Date(), { message: "Too young!" });
Supporting date strings
To write a schema that accepts either a Date
or a date string, use z.preprocess
.
const dateSchema = z.preprocess((arg) => {
if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
}, z.date());
type DateSchema = z.infer<typeof dateSchema>;
// type DateSchema = Date
dateSchema.safeParse(new Date("1/12/22")); // success: true
dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true
Zod enums
const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
type FishEnum = z.infer<typeof FishEnum>;
// 'Salmon' | 'Tuna' | 'Trout'
z.enum
is a Zod-native way to declare a schema with a fixed set of allowable string values. Pass the array of values directly into z.enum()
. Alternatively, use as const
to define your enum values as a tuple of strings. See the const assertion docs for details.
const VALUES = ["Salmon", "Tuna", "Trout"] as const;
const FishEnum = z.enum(VALUES);
This is not allowed, since Zod isn't able to infer the exact values of each element.
const fish = ["Salmon", "Tuna", "Trout"];
const FishEnum = z.enum(fish);
Autocompletion
To get autocompletion with a Zod enum, use the .enum
property of your schema:
FishEnum.enum.Salmon; // => autocompletes
FishEnum.enum;
/*
=> {
Salmon: "Salmon",
Tuna: "Tuna",
Trout: "Trout",
}
*/
You can also retrieve the list of options as a tuple with the .options
property:
FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
Native enums
Zod enums are the recommended approach to defining and validating enums. But if you need to validate against an enum from a third-party library (or you don't want to rewrite your existing enums) you can use z.nativeEnum()
.
Numeric enums
enum Fruits {
Apple,
Banana,
}
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Banana); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse(1); // passes
FruitEnum.parse(3); // fails
String enums
enum Fruits {
Apple = "apple",
Banana = "banana",
Cantaloupe, // you can mix numerical and string enums
}
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits
FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Cantaloupe); // passes
FruitEnum.parse("apple"); // passes
FruitEnum.parse("banana"); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse("Cantaloupe"); // fails
Const enums
The .nativeEnum()
function works for as const
objects as well. ⚠️ as const
required TypeScript 3.4+!
const Fruits = {
Apple: "apple",
Banana: "banana",
Cantaloupe: 3,
} as const;
const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3
FruitEnum.parse("apple"); // passes
FruitEnum.parse("banana"); // passes
FruitEnum.parse(3); // passes
FruitEnum.parse("Cantaloupe"); // fails
You can access the underlying object with the .enum
property:
FruitEnum.enum.Apple; // "apple"
Optionals
You can make any schema optional with z.optional()
. This wraps the schema in a ZodOptional
instance and returns the result.
const schema = z.optional(z.string());
schema.parse(undefined); // => returns undefined
type A = z.infer<typeof schema>; // string | undefined
For convenience, you can also call the .optional()
method on an existing schema.
const user = z.object({
username: z.string().optional(),
});
type C = z.infer<typeof user>; // { username?: string | undefined };
You can extract the wrapped schema from a ZodOptional
instance with .unwrap()
.
const stringSchema = z.string();
const optionalString = stringSchema.optional();
optionalString.unwrap() === stringSchema; // true
Nullables
Similarly, you can create nullable types with z.nullable()
.
const nullableString = z.nullable(z.string());
nullableString.parse("asdf"); // => "asdf"
nullableString.parse(null); // => null
Or use the .nullable()
method.
const E = z.string().nullable(); // equivalent to nullableString
type E = z.infer<typeof E>; // string | null
Extract the inner schema with .unwrap()
.
const stringSchema = z.string();
const nullableString = stringSchema.nullable();
nullableString.unwrap() === stringSchema; // true
Objects
// all properties are required by default
const Dog = z.object({
name: z.string(),
age: z.number(),
});
// extract the inferred type like this
type Dog = z.infer<typeof Dog>;
// equivalent to:
type Dog = {
name: string;
age: number;
};
.shape
Use .shape
to access the schemas for a particular key.
Dog.shape.name; // => string schema
Dog.shape.age; // => number schema
.keyof
Use .keyof
to create a ZodEnum
schema from the keys of an object schema.
const keySchema = Dog.keyof();
keySchema; // ZodEnum<["name", "age"]>
.extend
You can add additional fields to an object schema with the .extend
method.
const DogWithBreed = Dog.extend({
breed: z.string(),
});
You can use .extend
to overwrite fields! Be careful with this power!
.merge
Equivalent to A.extend(B.shape)
.
const BaseTeacher = z.object({ students: z.array(z.string()) });
const HasID = z.object({ id: z.string() });
const Teacher = BaseTeacher.merge(HasID);
type Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string }
If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B.
.pick/.omit
Inspired by TypeScript's built-in Pick
and Omit
utility types, all Zod object schemas have .pick
and .omit
methods that return a modified version. Consider this Recipe schema:
const Recipe = z.object({
id: z.string(),
name: z.string(),
ingredients: z.array(z.string()),
});
To only keep certain keys, use .pick
.
const JustTheName = Recipe.pick({ name: true });
type JustTheName = z.infer<typeof JustTheName>;
// => { name: string }
To remove certain keys, use .omit
.
const NoIDRecipe = Recipe.omit({ id: true });
type NoIDRecipe = z.infer<typeof NoIDRecipe>;
// => { name: string, ingredients: string[] }
.partial
Inspired by the built-in TypeScript utility type Partial, the .partial
method makes all properties optional.
Starting from this object:
const user = z.object({
email: z.string()
username: z.string(),
});
// { email: string; username: string }
We can create a partial version:
const partialUser = user.partial();
// { email?: string | undefined; username?: string | undefined }
You can also specify which properties to make optional:
const optionalEmail = user.partial({
email: true,
});
/*
{
email?: string | undefined;
username: string
}
*/
.deepPartial
The .partial
method is shallow — it only applies one level deep. There is also a "deep" version:
const user = z.object({
username: z.string(),
location: z.object({
latitude: z.number(),
longitude: z.number(),
}),
strings: z.array(z.object({ value: z.string() })),
});
const deepPartialUser = user.deepPartial();
/*
{
username?: string | undefined,
location?: {
latitude?: number | undefined;
longitude?: number | undefined;
} | undefined,
strings?: { value?: string}[]
}
*/
Important limitation: deep partials only work as expected in hierarchies of objects, arrays, and tuples.
.required
Contrary to the .partial
method, the .required
method makes all properties required.
Starting from this object:
const user = z.object({
email: z.string()
username: z.string(),
}).partial();
// { email?: string | undefined; username?: string | undefined }
We can create a required version:
const requiredUser = user.required();
// { email: string; username: string }
You can also specify which properties to make required:
const requiredEmail = user.required({
email: true,
});
/*
{
email: string;
username?: string | undefined;
}
*/
.passthrough
By default Zod object schemas strip out unrecognized keys during parsing.
const person = z.object({
name: z.string(),
});
person.parse({
name: "bob dylan",
extraKey: 61,
});
// => { name: "bob dylan" }
// extraKey has been stripped
Instead, if you want to pass through unknown keys, use .passthrough()
.
person.passthrough().parse({
name: "bob dylan",
extraKey: 61,
});
// => { name: "bob dylan", extraKey: 61 }
.strict
By default Zod object schemas strip out unrecognized keys during parsing. You can disallow unknown keys with .strict()
. If there are any unknown keys in the input, Zod will throw an error.
const person = z
.object({
name: z.string(),
})
.strict();
person.parse({
name: "bob dylan",
extraKey: 61,
});
// => throws ZodError
.strip
You can use the .strip
method to reset an object schema to the default behavior (stripping unrecognized keys).
.catchall
You can pass a "catchall" schema into an object schema. All unknown keys will be validated against it.
const person = z
.object({
name: z.string(),
})
.catchall(z.number());
person.parse({
name: "bob dylan",
validExtraKey: 61, // works fine
});
person.parse({
name: "bob dylan",
validExtraKey: false, // fails
});
// => throws ZodError
Using .catchall()
obviates .passthrough()
, .strip()
, or .strict()
. All keys are now considered "known".
Arrays
const stringArray = z.array(z.string());
// equivalent
const stringArray = z.string().array();
Be careful with the .array()
method. It returns a new ZodArray
instance. This means the order in which you call methods matters. For instance:
z.string().optional().array(); // (string | undefined)[]
z.string().array().optional(); // string[] | undefined
.element
Use .element
to access the schema for an element of the array.
stringArray.element; // => string schema
.nonempty
If you want to ensure that an array contains at least one element, use .nonempty()
.
const nonEmptyStrings = z.string().array().nonempty();
// the inferred type is now
// [string, ...string[]]
nonEmptyStrings.parse([]); // throws: "Array cannot be empty"
nonEmptyStrings.parse(["Ariana Grande"]); // passes
You can optionally specify a custom error message:
// optional custom error message
const nonEmptyStrings = z.string().array().nonempty({
message: "Can't be empty!",
});
.min/.max/.length
z.string().array().min(5); // must contain 5 or more items
z.string().array().max(5); // must contain 5 or fewer items
z.string().array().length(5); // must contain 5 items exactly
Unlike .nonempty()
these methods do not change the inferred type.
Tuples
Unlike arrays, tuples have a fixed number of elements and each element can have a different type.
const athleteSchema = z.tuple([
z.string(), // name
z.number(), // jersey number
z.object({
pointsScored: z.number(),
}), // statistics
]);
type Athlete = z.infer<typeof athleteSchema>;
// type Athlete = [string, number, { pointsScored: number }]
A variadic ("rest") argument can be added with the .rest
method.
const variadicTuple = z.tuple([z.string()]).rest(z.number());
const result = variadicTuple.parse(["hello", 1, 2, 3]);
// => [string, ...number[]];
Unions
Zod includes a built-in z.union
method for composing "OR" types.
const stringOrNumber = z.union([z.string(), z.number()]);
stringOrNumber.parse("foo"); // passes
stringOrNumber.parse(14); // passes
Zod will test the input against each of the "options" in order and return the first value that validates successfully.
For convenience, you can also use the .or
method:
const stringOrNumber = z.string().or(z.number());
Discriminated unions
A discriminated union is a union of object schemas that all share a particular key.
type MyUnion =
| { status: "success"; data: string }
| { status: "failed"; error: Error };
Such unions can be represented with the z.discriminatedUnion
method. This enables faster evaluation, because Zod can check the discriminator key (status
in the example above) ot determine which schema should be used to parse the input. This makes parsing more efficient and lets Zod provide report friendlier errors.
With the basic union method the input is tested against each of the provided "options", and in the case of invalidity, issues for all the "options" are shown in the zod error. On the other hand, the discriminated union allows for selecting just one of the "options", testing against it, and showing only the issues related to this "option".
const myUnion = z.discriminatedUnion("status", [
z.object({ status: z.literal("success"), data: z.string() }),
z.object({ status: z.literal("failed"), error: z.instanceof(Error) }),
]);
myUnion.parse({ type: "success", data: "yippie ki yay" });
Records
Record schemas are used to validate types such as { [k: string]: number }
.
If you want to validate the values of an object against some schema but don't care about the keys, use z.record(valueType)
:
const NumberCache = z.record(z.number());
type NumberCache = z.infer<typeof NumberCache>;
// => { [k: string]: number }
This is particularly useful for storing or caching items by ID.
const userStore: UserStore = {};
userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
name: "Carlotta",
}; // passes
userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
whatever: "Ice cream sundae",
}; // TypeError
Record key type
If you want to validate both the keys and the values, use
z.record(keyType, valueType)
:
const NoEmptyKeysSchema = z.record(z.string().min(1), z.number());
NoEmptyKeysSchema.parse({ count: 1 }); // => { 'count': 1 }
NoEmptyKeysSchema.parse({ "": 1 }); // fails
(Notice how when passing two arguments, valueType
is the second argument)
A note on numerical keys
While z.record(keyType, valueType)
is able to accept numerical key types and TypeScript's built-in Record type is Record<KeyType, ValueType>
, it's hard to represent the TypeScript type Record<number, any>
in Zod.
As it turns out, TypeScript's behavior surrounding [k: number]
is a little unintuitive:
const testMap: { [k: number]: string } = {
1: "one",
};
for (const key in testMap) {
console.log(`${key}: ${typeof key}`);
}
// prints: `1: string`
As you can see, JavaScript automatically casts all object keys to strings under the hood. Since Zod is trying to bridge the gap between static and runtime types, it doesn't make sense to provide a way of creating a record schema with numerical keys, since there's no such thing as a numerical key in runtime JavaScript.
Maps
const stringNumberMap = z.map(z.string(), z.number());
type StringNumberMap = z.infer<typeof stringNumberMap>;
// type StringNumberMap = Map<string, number>
Sets
const numberSet = z.set(z.number());
type NumberSet = z.infer<typeof numberSet>;
// type NumberSet = Set<number>
Set schemas can be further contrainted with the following utility methods.
z.set(z.string()).nonempty(); // must contain at least one item
z.set(z.string()).min(5); // must contain 5 or more items
z.set(z.string()).max(5); // must contain 5 or fewer items
z.set(z.string()).size(5); // must contain 5 items exactly
Intersections
Intersections are useful for creating "logical AND" types. This is useful for intersecting two object types.
const Person = z.object({
name: z.string(),
});
const Employee = z.object({
role: z.string(),
});
const EmployedPerson = z.intersection(Person, Employee);
// equivalent to:
const EmployedPerson = Person.and(Employee);
Though in many cases, it is recommended to use A.merge(B)
to merge two objects. The .merge
method returns a new ZodObject
instance, whereas A.and(B)
returns a less useful ZodIntersection
instance that lacks common object methods like pick
and omit
.
const a = z.union([z.number(), z.string()]);
const b = z.union([z.number(), z.boolean()]);
const c = z.intersection(a, b);
type c = z.infer<typeof c>; // => number
Recursive types
You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint".
interface Category {
name: string;
subcategories: Category[];
}
// cast to z.ZodType<Category>
const Category: z.ZodType<Category> = z.lazy(() =>
z.object({
name: z.string(),
subcategories: z.array(Category),
})
);
Category.parse({
name: "People",
subcategories: [
{
name: "Politicians",
subcategories: [{ name: "Presidents", subcategories: [] }],
},
],
}); // passes
Unfortunately this code is a bit duplicative, since you're declaring the types twice: once in the interface and again in the Zod definition.
JSON type
If you want to validate any JSON value, you can use the snippet below.
const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
type Literal = z.infer<typeof literalSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const jsonSchema: z.ZodType<Json> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
);
jsonSchema.parse(data);
Thanks to ggoodman for suggesting this.
Cyclical objects
Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop.
Promises
const numberPromise = z.promise(z.number());
"Parsing" works a little differently with promise schemas. Validation happens in two parts:
- Zod synchronously checks that the input is an instance of Promise (i.e. an object with
.then
and .catch
methods.).
- Zod uses
.then
to attach an additional validation step onto the existing Promise. You'll have to use .catch
on the returned Promise to handle validation failures.
numberPromise.parse("tuna");
// ZodError: Non-Promise type: string
numberPromise.parse(Promise.resolve("tuna"));
// => Promise<number>
const test = async () => {
await numberPromise.parse(Promise.resolve("tuna"));
// ZodError: Non-number type: string
await numberPromise.parse(Promise.resolve(3.14));
// => 3.14
};
Instanceof
You can use z.instanceof
to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries.
class Test {
name: string;
}
const TestSchema = z.instanceof(Test);
const blob: any = "whatever";
TestSchema.parse(new Test()); // passes
TestSchema.parse("blob"); // throws
Function schemas
Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic".
You can create a function schema with z.function(args, returnType)
.
const myFunction = z.function();
type myFunction = z.infer<typeof myFunction>;
// => ()=>unknown
Define inputs and outputs.
const myFunction = z
.function()
.args(z.string(), z.number()) // accepts an arbitrary number of arguments
.returns(z.boolean());
type myFunction = z.infer<typeof myFunction>;
// => (arg0: string, arg1: number)=>boolean
Function schemas have an .implement()
method which accepts a function and returns a new function that automatically validates its inputs and outputs.
const trimmedLength = z
.function()
.args(z.string()) // accepts an arbitrary number of arguments
.returns(z.number())
.implement((x) => {
// TypeScript knows x is a string!
return x.trim().length;
});
trimmedLength("sandwich"); // => 8
trimmedLength(" asdf "); // => 4
If you only care about validating inputs, just don't call the .returns()
method. The output type will be inferred from the implementation.
You can use the special z.void()
option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)
const myFunction = z
.function()
.args(z.string())
.implement((arg) => {
return [arg.length]; //
});
myFunction; // (arg: string)=>number[]
Extract the input and output schemas from a function schema.
myFunction.parameters();
// => ZodTuple<[ZodString, ZodNumber]>
myFunction.returnType();
// => ZodBoolean
Preprocess
Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the .transform docs.)
But sometimes you want to apply some transform to the input before parsing happens. A common use case: type coercion. Zod enables this with the z.preprocess()
.
const castToString = z.preprocess((val) => String(val), z.string());
This returns a ZodEffects
instance. ZodEffects
is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.
Schema methods
All Zod schemas contain certain methods.
.parse
.parse(data: unknown): T
Given any Zod schema, you can call its .parse
method to check data
is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.
IMPORTANT: The value returned by .parse
is a deep clone of the variable you passed in.
const stringSchema = z.string();
stringSchema.parse("fish"); // => returns "fish"
stringSchema.parse(12); // throws Error('Non-string type: number');
.parseAsync
.parseAsync(data:unknown): Promise<T>
If you use asynchronous refinements or transforms (more on those later), you'll need to use .parseAsync
const stringSchema1 = z.string().refine(async (val) => val.length < 20);
const value1 = await stringSchema.parseAsync("hello"); // => hello
const stringSchema2 = z.string().refine(async (val) => val.length > 20);
const value2 = await stringSchema.parseAsync("hello"); // => throws
.safeParse
.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }
If you don't want Zod to throw errors when validation fails, use .safeParse
. This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.
stringSchema.safeParse(12);
// => { success: false; error: ZodError }
stringSchema.safeParse("billie");
// => { success: true; data: 'billie' }
The result is a discriminated union so you can handle errors very conveniently:
const result = stringSchema.safeParse("billie");
if (!result.success) {
// handle error then return
result.error;
} else {
// do something
result.data;
}
.safeParseAsync
Alias: .spa
An asynchronous version of safeParse
.
await stringSchema.safeParseAsync("billie");
For convenience, this has been aliased to .spa
:
await stringSchema.spa("billie");
.refine
.refine(validator: (data:T)=>any, params?: RefineParams)
Zod lets you provide custom validation logic via refinements. (For advanced features like creating multiple issues and customizing error codes, see .superRefine
.)
Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an integer or that a string is a valid email address.
For example, you can define a custom validation check on any Zod schema with .refine
:
const myString = z.string().refine((val) => val.length <= 255, {
message: "String can't be more than 255 characters",
});
⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure.
Arguments
As you can see, .refine
takes two arguments.
- The first is the validation function. This function takes one input (of type
T
— the inferred type of the schema) and returns any
. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
- The second argument accepts some options. You can use this to customize certain error-handling behavior:
type RefineParams = {
// override error message
message?: string;
// appended to error path
path?: (string | number)[];
// params object you can use to customize message
// in error map
params?: object;
};
For advanced cases, the second argument can also be a function that returns RefineParams
/
z.string().refine(
(val) => val.length > 10,
(val) => ({ message: `${val} is not more than 10 characters` })
);
Customize error path
const passwordForm = z
.object({
password: z.string(),
confirm: z.string(),
})
.refine((data) => data.password === data.confirm, {
message: "Passwords don't match",
path: ["confirm"], // path of error
})
.parse({ password: "asdf", confirm: "qwer" });
Because you provided a path
parameter, the resulting error will be:
ZodError {
issues: [{
"code": "custom",
"path": [ "confirm" ],
"message": "Passwords don't match"
}]
}
Asynchronous refinements
Refinements can also be async:
const userId = z.string().refine(async (id) => {
// verify that ID exists in database
return true;
});
⚠️ If you use async refinements, you must use the .parseAsync
method to parse data! Otherwise Zod will throw an error.
Transforms and refinements can be interleaved:
z.string()
.transform((val) => val.length)
.refine((val) => val > 25);
.superRefine
The .refine
method is actually syntactic sugar atop a more versatile (and verbose) method called superRefine
. Here's an example:
const Strings = z.array(z.string()).superRefine((val, ctx) => {
if (val.length > 3) {
ctx.addIssue({
code: z.ZodIssueCode.too_big,
maximum: 3,
type: "array",
inclusive: true,
message: "Too many items ????",
});
}
if (val.length !== new Set(val).size) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `No duplicates allowed.`,
});
}
});
You can add as many issues as you like. If ctx.addIssue
is not called during the execution of the function, validation passes.
Normally refinements always create issues with a ZodIssueCode.custom
error code, but with superRefine
you can create any issue of any code. Each issue code is described in detail in the Error Handling guide: ERROR_HANDLING.md.
Abort early
By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to abort early to prevent later refinements from being executed. To achieve this, pass the fatal
flag to ctx.addIssue
and return z.NEVER
.
const schema = z.number().superRefine((val, ctx) => {
if (val < 10) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "should be >= 10",
fatal: true,
});
return z.NEVER;
}
if (val !== 12) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "should be twelve",
});
}
});
To transform data after parsing, use the transform
method.
const stringToNumber = z.string().transform((val) => val.length);
stringToNumber.parse("string"); // => 6
Chaining order
Note that stringToNumber
above is an instance of the ZodEffects
subclass. It is NOT an instance of ZodString
. If you want to use the built-in methods of ZodString
(e.g. .email()
) you must apply those methods before any transforms.
const emailToDomain = z
.string()
.email()
.transform((val) => val.split("@")[1]);
emailToDomain.parse("colinhacks@example.com"); // => example.com
The .transform
method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining refine
and validate
.
As with .superRefine
, the transform function receives a ctx
object with a addIssue
method that can be used to register validation issues.
const Strings = z.string().transform((val, ctx) => {
const parsed = parseInt(val);
if (isNaN(parsed)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Not a number",
});
// This is a special symbol you can use to
// return early from the transform function.
// It has type `never` so it does not affect the
// inferred return type.
return z.NEVER;
}
return parsed;
});
Relationship to refinements
Transforms and refinements can be interleaved. These will be executed in the order they are declared.
z.string()
.transform((val) => val.toUpperCase())
.refine((val) => val.length > 15)
.transform((val) => `Hello ${val}`)
.refine((val) => val.indexOf("!") === -1);
Transforms can also be async.
const IdToUser = z
.string()
.uuid()
.transform(async (id) => {
return await getUserById(id);
});
⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error.
.default
You can use transforms to implement the concept of "default values" in Zod.
const stringWithDefault = z.string().default("tuna");
stringWithDefault.parse(undefined); // => "tuna"
Optionally, you can pass a function into .default
that will be re-executed whenever a default value needs to be generated:
const numberWithRandomDefault = z.number().default(Math.random);
numberWithRandomDefault.parse(undefined); // => 0.4413456736055323
numberWithRandomDefault.parse(undefined); // => 0.1871840107401901
numberWithRandomDefault.parse(undefined); // => 0.7223408162401552
Conceptually, this is how Zod processes default values:
- If the input is
undefined
, the default value is returned
- Otherwise, the data is parsed using the base schema
.catch
Use .catch()
to provide a "catch value" to be returned in the event of a parsing error.
const numberWithCatch = z.number().catch(42);
numberWithCatch.parse(5); // => 5
numberWithCatch.parse("tuna"); // => 42
Optionally, you can pass a function into .catch
that will be re-executed whenever a default value needs to be generated:
const numberWithRandomCatch = z.number().catch(Math.random);
numberWithRandomDefault.parse("sup"); // => 0.4413456736055323
numberWithRandomDefault.parse("sup"); // => 0.1871840107401901
numberWithRandomDefault.parse("sup"); // => 0.7223408162401552
Conceptually, this is how Zod processes "catch values":
- The data is parsed using the base schema
- If the parsing fails, the "catch value" is returned
.optional
A convenience method that returns an optional version of a schema.
const optionalString = z.string().optional(); // string | undefined
// equivalent to
z.optional(z.string());
.nullable
A convenience method that returns a nullable version of a schema.
const nullableString = z.string().nullable(); // string | null
// equivalent to
z.nullable(z.string());
.nullish
A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both undefined
and null
. Read more about the concept of "nullish" in the TypeScript 3.7 release notes.
const nullishString = z.string().nullish(); // string | null | undefined
// equivalent to
z.string().optional().nullable();
.array
A convenience method that returns an array schema for the given type:
const nullableString = z.string().array(); // string[]
// equivalent to
z.array(z.string());
.promise
A convenience method for promise types:
const stringPromise = z.string().promise(); // Promise<string>
// equivalent to
z.promise(z.string());
.or
A convenience method for union types.
z.string().or(z.number()); // string | number
// equivalent to
z.union([z.string(), z.number()]);
.and
A convenience method for creating intersection types.
z.object({ name: z.string() }).and(z.object({ age: z.number() })); // { name: string } & { age: number }
// equivalent to
z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));
.brand
.brand<T>() => ZodBranded<this, B>
TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same.
type Cat = { name: string };
type Dog = { name: string };
const petCat = (cat: Cat) => {};
const fido: Dog = { name: "fido" };
petCat(fido); // works fine
In some cases, its can be desirable to simulate nominal typing inside TypeScript. For instance, you may wish to write a function that only accepts an input that has been validated by Zod. This can be achieved with branded types (AKA opaque types).
const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;
const petCat = (cat: Cat) => {};
// this works
const simba = Cat.parse({ name: "simba" });
petCat(simba);
// this doesn't
petCat({ name: "fido" });
Under the hood, this works by attaching a "brand" to the inferred type using an intersection type. This way, plain/unbranded data structures are no longer assignable to the inferred type of the schema.
const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;
// {name: string} & {[symbol]: "Cat"}
Note that branded types do not affect the runtime result of .parse
. It is a static-only construct.
Guides and concepts
Type inference
You can extract the TypeScript type of any schema with z.infer<typeof mySchema>
.
const A = z.string();
type A = z.infer<typeof A>; // string
const u: A = 12; // TypeError
const u: A = "asdf"; // compiles
What about transforms?
In reality each Zod schema internally tracks two types: an input and an output. For most schemas (e.g. z.string()
) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance z.string().transform(val => val.length)
has an input of string
and an output of number
.
You can separately extract the input and output types like so:
const stringToNumber = z.string().transform((val) => val.length);
// ⚠️ Important: z.infer returns the OUTPUT type!
type input = z.input<typeof stringToNumber>; // string
type output = z.output<typeof stringToNumber>; // number
// equivalent to z.output!
type inferred = z.infer<typeof stringToNumber>; // number
Writing generic functions
When attempting to write a functions that accepts a Zod schemas as an input, it's common to try something like this:
function makeSchemaOptional<T>(schema: z.ZodType<T>) {
return schema.optional();
}
This approach has some issues. The schema
variable in this function is typed as an instance of ZodType
, which is an abstract class that all Zod schemas inherit from. This approach loses type information, namely which subclass the input actually is.
const arg = makeSchemaOptional(z.string());
arg.unwrap();
A better approach is for the generate parameter to refer to the schema as a whole.
function makeSchemaOptional<T extends z.ZodTypeAny>(schema: T) {
return schema.optional();
}
ZodTypeAny
is just a shorthand for ZodType<any, any, any>
, a type that is broad enough to match any Zod schema.
As you can see, schema
is now fully and properly typed.
const arg = makeSchemaOptional(z.string());
arg.unwrap(); // ZodString
The ZodType
class has three generic parameters.
class ZodType<
Output = any,
Def extends ZodTypeDef = ZodTypeDef,
Input = Output
> { ... }
By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function:
function makeSchemaOptional<T extends z.ZodType<string>>(schema: T) {
return schema.optional();
}
makeSchemaOptional(z.string());
// works fine
makeSchemaOptional(z.number());
// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>'
Error handling
Zod provides a subclass of Error called ZodError
. ZodErrors contain an issues
array containing detailed information about the validation problems.
const data = z
.object({
name: z.string(),
})
.safeParse({ name: 12 });
if (!data.success) {
data.error.issues;
/* [
{
"code": "invalid_type",
"expected": "string",
"received": "number",
"path": [ "name" ],
"message": "Expected string, received number"
}
] */
}
For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: ERROR_HANDLING.md
Zod's error reporting emphasizes completeness and correctness. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third party library like zod-validation-error
You can use the .format()
method to convert this error into a nested object.
const data = z
.object({
name: z.string(),
})
.safeParse({ name: 12 });
if (!data.success) {
const formatted = data.error.format();
/* {
name: { _errors: [ 'Expected string, received number' ] }
} */
formatted.name?._errors;
// => ["Expected string, received number"]
}
Comparison
There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience.
<!-- | Feature | Zod | Joi | Yup | io-ts | [Runtypes](https://github.com/pelo