Capítulo 11 de 61

Chapter 11: Enums

Core Idea

z.enum() validates a value against a fixed set of allowed values, accepting string arrays, enum-like object literals, or TypeScript enums, and is the recommended replacement for the deprecated z.nativeEnum().

Key Concepts

  • z.enum([...values]): pass the array literal directly (or with as const) so TypeScript can infer the exact union type — a variable-typed array widens to string.
  • z.enum({ Key: value, ... }): accepts enum-like object literals ({ [key: string]: string | number }).
  • z.enum(SomeTsEnum): accepts an externally declared TypeScript enum directly — this is the current way to validate TS enums; z.nativeEnum() is deprecated.
  • .enum: exposes the schema's values as a plain object ({ Salmon: "Salmon", ... }); in Zod Mini, use .def.entries instead.
  • .exclude([...]) / .extract([...]): derive a new, narrower enum schema by removing or keeping specific values (Zod only — no Zod Mini equivalent).

Code Examples

const FishEnum = z.enum(["Salmon", "Tuna", "Trout"] as const);
FishEnum.parse("Salmon");   // ok
FishEnum.parse("Swordfish"); // throws

const TunaOnly = FishEnum.exclude(["Salmon", "Trout"]);
const SalmonAndTroutOnly = FishEnum.extract(["Salmon", "Trout"]);
  • What it demonstrates: as const preserves the literal union type; .exclude()/.extract() derive related enum schemas without redeclaring the values.

Anti-patterns

  • Passing a plain string[] variable to z.enum(): without as const (or a literal array inline), the inferred type widens to string, losing the whole point of an enum schema.
  • Using z.nativeEnum(): deprecated — pass the TS enum directly to z.enum() instead.

Key Takeaways

  1. Always pass either a literal array or an as const-asserted array to z.enum() — a plain variable loses type precision.
  2. z.enum() now covers string arrays, object-literal enums, and TS enums in one API — no need for a separate native-enum function.
  3. .exclude()/.extract() are Zod-only (not in Zod Mini) conveniences for deriving related enum schemas.

Connects To

  • Literals: for a single exact value rather than a named set.
  • Discriminated unions: enum schemas are common discriminant field types.