字面量
Zod 可以验证具体的字面量值。
基本用法
ts
import { z } from "zod";
// 字符串字面量
const tuna = z.literal("tuna");
tuna.parse("tuna"); // => "tuna"
tuna.parse("salmon"); // 抛出 ZodError
// 数字字面量
const twelve = z.literal(12);
twelve.parse(12); // => 12
twelve.parse(11); // 抛出 ZodError
// 布尔字面量
const tru = z.literal(true);
tru.parse(true); // => true
tru.parse(false); // 抛出 ZodError
// BigInt 字面量
const twobig = z.literal(2n);
twobig.parse(2n); // => 2n
twobig.parse(3n); // 抛出 ZodError
Symbol 字面量
ts
const sym = Symbol("foo");
const symLiteral = z.literal(sym);
symLiteral.parse(sym); // => Symbol(foo)
symLiteral.parse(Symbol("foo")); // 抛出 ZodError
获取字面量的值
你可以使用 .value
属性来获取字面量的值:
ts
const tuna = z.literal("tuna");
console.log(tuna.value); // "tuna"
const twelve = z.literal(12);
console.log(twelve.value); // 12
组合字面量
字面量可以与其他 Zod 类型组合使用:
ts
// 联合类型
const fish = z.union([z.literal("tuna"), z.literal("salmon")]);
fish.parse("tuna"); // => "tuna"
fish.parse("salmon"); // => "salmon"
fish.parse("trout"); // 抛出 ZodError
// 对象中的字面量
const User = z.object({
role: z.literal("admin"),
name: z.string(),
});
User.parse({ role: "admin", name: "Bob" }); // 通过
User.parse({ role: "user", name: "Bob" }); // 抛出 ZodError
类型推断
使用 z.infer
来获取字面量类型:
ts
const tuna = z.literal("tuna");
type Tuna = z.infer<typeof tuna>; // "tuna"
const Status = z.union([
z.literal("pending"),
z.literal("success"),
z.literal("error"),
]);
type Status = z.infer<typeof Status>; // "pending" | "success" | "error"