Capítulo 18 de 61

Chapter 18: Arrays & Tuples

Core Idea

z.array() validates a variable-length list where every element matches one schema; z.tuple() validates a fixed-length list where each position has its own schema, optionally followed by a variadic rest.

Key Concepts

  • z.array(schema) (or schema.array()): every element must match the given schema. .unwrap() (Zod) / .def.element (Zod Mini) gets the element schema back.
  • .nonempty() / .min() / .max() / .length(): array length constraints, same shape as string length checks.
  • z.tuple([schemaA, schemaB, ...]): fixed-length, position-specific validation — [string, number, boolean] in the example accepts exactly 3 elements of those respective types.
  • z.tuple([...fixed], restSchema): adds a variadic rest parameter after the fixed positions, e.g. [string, ...number[]].

Code Examples

const stringArray = z.array(z.string());
z.array(z.string()).nonempty(); // at least 1 item
z.array(z.string()).length(5);  // exactly 5 items

const MyTuple = z.tuple([z.string(), z.number(), z.boolean()]);
// [string, number, boolean]

const variadicTuple = z.tuple([z.string()], z.number());
// [string, ...number[]]
  • What it demonstrates: arrays validate homogeneous lists of any length; tuples validate heterogeneous, position-specific lists, optionally with a variadic tail.

Key Takeaways

  1. Reach for z.tuple() instead of z.array() when position matters and the length is fixed (e.g. [lat, lng] coordinate pairs, CSV rows with known columns).
  2. Tuple rest parameters (z.tuple([...], restSchema)) let you keep strict typing on leading positions while allowing an open-ended tail.
  3. Array length checks (.nonempty(), .min(), .max(), .length()) mirror the string-length API for consistency.

Connects To

  • Records: for a dictionary keyed by arbitrary strings, as opposed to an ordered list.
  • Unions: tuples commonly combine with unions when different positions can be one of several shapes.