Literals
Zod can validate specific literal values.
Basic Usage
ts
import { z } from "zod";
// String literals
const tuna = z.literal("tuna");
tuna.parse("tuna"); // => "tuna"
tuna.parse("salmon"); // throws ZodError
// Number literals
const twelve = z.literal(12);
twelve.parse(12); // => 12
twelve.parse(11); // throws ZodError
// Boolean literals
const tru = z.literal(true);
tru.parse(true); // => true
tru.parse(false); // throws ZodError
// BigInt literals
const twobig = z.literal(2n);
twobig.parse(2n); // => 2n
twobig.parse(3n); // throws ZodError
Symbol Literals
ts
const sym = Symbol("foo");
const symLiteral = z.literal(sym);
symLiteral.parse(sym); // => Symbol(foo)
symLiteral.parse(Symbol("foo")); // throws ZodError
Accessing Literal Values
You can access the literal value using the .value
property:
ts
const tuna = z.literal("tuna");
console.log(tuna.value); // "tuna"
const twelve = z.literal(12);
console.log(twelve.value); // 12
Combining Literals
Literals can be combined with other Zod types:
ts
// Union types
const fish = z.union([z.literal("tuna"), z.literal("salmon")]);
fish.parse("tuna"); // => "tuna"
fish.parse("salmon"); // => "salmon"
fish.parse("trout"); // throws ZodError
// Objects with literals
const User = z.object({
role: z.literal("admin"),
name: z.string(),
});
User.parse({ role: "admin", name: "Bob" }); // passes
User.parse({ role: "user", name: "Bob" }); // throws ZodError
Type Inference
Use z.infer
to get the literal type:
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"