Capítulo 22 de 61

Chapter 22: Maps & Sets

Core Idea

z.map() and z.set() validate actual Map/Set instances (not plain objects or arrays), with size constraints mirroring the array/string length API.

Key Concepts

  • z.map(keySchema, valueSchema): validates a real Map instance whose keys and values each match their schema.
  • z.set(valueSchema): validates a real Set instance whose elements match the schema.
  • Size constraints: .nonempty() (at least 1), .min(n), .max(n), .size(n) (exact) — same shape as array length checks, but operating on Map/Set size instead of array length.

Code Examples

const StringNumberMap = z.map(z.string(), z.number()); // Map<string, number>
const myMap = new Map();
myMap.set("one", 1);
StringNumberMap.parse(myMap);

z.map(z.string(), z.number()).min(5);   // at least 5 entries
z.map(z.string(), z.number()).size(5);  // exactly 5 entries

const NumberSet = z.set(z.number()); // Set<number>
z.set(z.string()).nonempty();  // at least 1 item
z.set(z.string()).max(5);      // at most 5 items
  • What it demonstrates: z.map()/z.set() validate the runtime Map/Set type itself, with the same length-style constraint vocabulary used elsewhere.

Anti-patterns

  • Passing a plain object where a Map schema is expected: z.map() requires an actual Map instance — a plain { key: value } object fails validation even if its shape looks equivalent.

Key Takeaways

  1. z.map()/z.set() are for validating genuine Map/Set instances — for plain-object dictionaries, use z.record() instead.
  2. Size constraints on maps/sets use the same .min()/.max()/.nonempty() vocabulary as arrays and strings, for consistency across the API.

Connects To

  • Records: the plain-object equivalent of z.map() for dictionary-shaped data.
  • Arrays & Tuples: the ordered-list equivalent, with the same size-constraint methods.