Literal values in Zod
Literal schemas represent a literal type, such as the string "tuna" or the number 12. You can also pass an array to allow several exact values.
How it works
- Single literal values.
z.literal("tuna")andz.literal(12)each describe one value. The code tests a matching and a non-matching input for each. [1] - Multiple allowed values. Passing an array,
z.literal(["red", "green", "blue"]), makes one schema for all three values. The code runssafeParseon several colors and prints whether each was accepted. [1] - Read the allowed set.
colors.valuesholds the allowed values as a Set. The code spreads it into an array to print it. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import * as z from "zod";
const tuna = z.literal("tuna");
const twelve = z.literal(12);
console.log("tuna <- 'tuna':", tuna.safeParse("tuna").success);
console.log("tuna <- 'salmon':", tuna.safeParse("salmon").success);
console.log("twelve <- 12:", twelve.safeParse(12).success);
console.log("twelve <- '12':", twelve.safeParse("12").success);
// several allowed values in one schema
const colors = z.literal(["red", "green", "blue"]);
for (const c of ["green", "blue", "yellow"]) {
const result = colors.safeParse(c);
console.log(`colors <- '${c}':`, result.success ? "accepted" : "rejected");
}
console.log("allowed values:", [...colors.values].join(", "));
Add "yellow" to the literal array and run again to see it pass. Code written by AgentGid [1].
Add "yellow" to the literal array and run again to see it pass. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with zod 4.6.6. Needs WebGL.
More Zod examples
Handling errors with ZodError in Zod String formats in Zod: email, UUID, phone, datetime String validation in Zod Type coercion in Zod
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.