Capítulo 3 de 61

Chapter 3: Literals

Core Idea

z.literal() schemas validate an exact value (a TypeScript literal type) rather than a general type — useful for tags, flags, and fixed constants.

Key Concepts

  • z.literal(value): matches one exact primitive value (string, number, bigint, or boolean).
  • z.null() / z.undefined() / z.void(): dedicated schemas for the null and undefined literals (z.void() is an alias for z.undefined()).
  • z.literal([...values]): matches any one of several literal values (a lightweight alternative to a union of literals).
  • .values: on a literal schema, exposes the Set of allowed literal values (Zod only, no Zod Mini equivalent).

Code Examples

const tuna = z.literal("tuna");
const twelve = z.literal(12);
const twobig = z.literal(2n);
const tru = z.literal(true);

const colors = z.literal(["red", "green", "blue"]);
colors.parse("green"); // ok
colors.parse("yellow"); // throws

colors.values; // => Set<"red" | "green" | "blue">
  • What it demonstrates: single-value and multi-value literal schemas, plus introspecting the allowed set.

Key Takeaways

  1. Use z.literal() for exact-value matches (discriminant tags, fixed config flags), not z.enum(), which is for named enum-like sets.
  2. z.literal([...]) is the concise form of "one of these exact values" — equivalent in effect to a union of individual literals.
  3. .values (Zod only) lets code introspect the allowed set at runtime, e.g. to build a <select> from a schema.

Connects To

  • Enums: for a named set of string values rather than raw literals.
  • Discriminated unions: literal schemas are the typical discriminant field type.