In Zod 4, when do you use z.array, z.tuple or z.record, and how does each treat extra or missing entries?
answer
- any length versus fixed positions
- rest element on a tuple
- record takes two schemas now
- enum keys are exhaustive
- partialRecord for optional keys
basics
~20 sUse z.array for a list of one type at any length, z.tuple for fixed positions with their own schemas, z.record(keySchema, valueSchema) for dynamic keys. A tuple without a rest schema rejects extra items; an enum-keyed record requires every key.
solid answer
~40 s`z.array(z.string())` accepts any number of strings, and length rules come from `.min()`, `.max()`, `.length()` and `.nonempty()`. `z.tuple([z.number(), z.number()])` fixes both length and per-position schemas: too few items fails with `too_small`, too many with `too_big`, unless you pass a rest schema as the second argument, as in `z.tuple([z.string()], z.number())`. `z.record(z.string(), z.number())` validates every key and every value of a dictionary. Zod 4 changed records in two ways: the single-argument form is dropped from the API, so it is a type error, and an enum key schema is exhaustive, so `z.record(z.enum(["math", "art"]), z.number())` fails when `art` is missing and reports any key outside the enum as unrecognized. Use `z.partialRecord` when the enum keys are optional.
code
typescript · 12 linesimport * as z from "zod";
const Tags = z.array(z.string()).max(10);
const Point = z.tuple([z.number(), z.number()]);
const Scores = z.record(z.enum(["math", "art"]), z.number());
const SomeScores = z.partialRecord(z.enum(["math", "art"]), z.number());
console.log(Tags.parse(["a", "b"])); // ["a", "b"]
console.log(Point.safeParse([1, 2, 3]).success); // false: too_big
console.log(Scores.safeParse({ math: 90 }).success); // false: art is missing
console.log(Scores.safeParse({ math: 90, art: 70, gym: 50 }).success); // false: gym is unrecognized
console.log(SomeScores.parse({ math: 90 })); // { math: 90 }go deeper
Know which schema matches which data: arrays for lists, tuples for fixed positions, records for dictionaries with dynamic keys. Remember z.record takes two schemas.
Explain what fails a tuple (too_small, too_big, rest schema) and why an enum-keyed record demands every key while a plain object strips unknown ones.
Spot the Zod 3 to 4 migration breaks in collections: single-argument records, enum-keyed records turning exhaustive, and nonempty losing its tuple type.
Decide when a dictionary-shaped payload should be a record or an explicit object, weighing exhaustive checks against tolerance for keys a newer client adds.
## Three ways to validate a collection Zod has a separate schema for each common collection shape. Picking the right one decides what counts as an extra or a missing entry. | Schema | Input it describes | Length or keys | Extra entries | Missing entries | |---|---|---|---|---| | `z.array(el)` | a list of one element type | any length unless constrained | not a concept: every item must match `el` | only by length checks | | `z.tuple([a, b])` | fixed positions, one schema each | fixed unless a rest schema is given | `too_big` issue | `too_small` issue | | `z.record(k, v)` | an object used as a dictionary | keys validated by `k` | depends on the key schema | enum keys are required | ## Arrays `z.array(z.string())`, or the method form `z.string().array()`, accepts a list of any length in which every element passes the element schema. An element that fails produces an issue whose path includes its index, such as `["tags", 2]`. Length rules are methods on the array schema: - `.min(n)` and `.max(n)` bound the item count. - `.length(n)` requires an exact count. - `.nonempty()` requires at least one item. In Zod 4, `.nonempty()` behaves exactly like `.min(1)`, and its inferred type stays `string[]`. Zod 3 inferred `[string, ...string[]]`; if you want that "at least one" type, write a tuple with a rest schema, `z.tuple([z.string()], z.string())`. `.unwrap()` returns the element schema when you need to reuse it. ## Tuples A **tuple** is an array whose positions mean different things, such as a `[latitude, longitude]` pair or a `[name, age, active]` row. `z.tuple([z.number(), z.number()])` checks each position against its own schema and checks the length: 1. Fewer items than the required positions fails with a `too_small` issue. 2. More items fails with a `too_big` issue, because a tuple without a rest schema has a fixed maximum. 3. A second argument adds a **rest** schema for any number of trailing items: `z.tuple([z.string()], z.number())` describes `[string, ...number[]]`. A tuple is the right tool when a protocol or a library hands you positional data; for named fields, an object schema reads better and produces clearer error paths. ## Records A **record** is an object whose keys are data, not a fixed shape: a map of user id to score, or locale code to translated string. `z.record(keySchema, valueSchema)` validates every key against the first schema and every value against the second. - **Pass both schemas in Zod 4.** Zod 3's single-argument `z.record(z.string())` is dropped from the API: its type signature rejects it and the changelog calls it no longer supported. A compatibility branch still reads a lone schema as the value schema at runtime, but do not rely on it; write `z.record(z.string(), z.string())`. - **Numeric keys** use `z.number()` or `z.int()` as the key schema; Zod checks that each key is a numeric string and applies constraints such as `.min()` or `.max()`. - **Enum keys are exhaustive.** With `z.enum(["math", "art"])` as the key schema, every enum value must be present, and the inferred type is `{ math: number; art: number }`. A missing key fails because its value is validated as `undefined` (unless the value schema accepts an absent value, for example through `.optional()` or `.default()`), and a key outside the enum is reported in an `unrecognized_keys` issue. - **`z.partialRecord`** skips the exhaustiveness check, so enum keys become optional, matching what Zod 3 inferred for an enum-keyed record. - **`z.looseRecord`** passes keys that do not match the key schema through unchanged instead of rejecting them. ## Records versus objects The contrast with `z.object` trips people up. A plain `z.object` **strips** keys it does not declare and still succeeds, while a record with an enum key schema **rejects** keys outside the enum. Choose an object when the keys are known field names with different value types, and a record when the keys come from data and every value shares one schema. A feature-flag map shows the choice inside records too. `z.record(z.string(), z.boolean())` accepts any flag name, which suits labels a user can invent. `z.record(z.enum(["beta", "darkMode"]), z.boolean())` insists that every known flag is present and rejects any other key, which suits a configuration file that must stay complete and must not carry stale entries. Element and value schemas can be any Zod schema, including other objects, so collections compose freely with the rest of the library.
- In Zod 4, how do you get the inferred type [string, ...string[]] that Zod 3's .nonempty() used to give?Use a tuple with a rest schema: `z.tuple([z.string()], z.string())`. In Zod 4, `.nonempty()` on an array is the same as `.min(1)`: it still rejects an empty list at runtime but leaves the inferred type as `string[]`.
- A Zod 3 codebase used z.record(z.string()). What do you change when moving it to Zod 4?Add the key schema explicitly: `z.record(z.string(), z.string())`. Zod 4 dropped the single-argument form from its API, so the old call is a type error; a runtime fallback still accepts it, but that is a compatibility branch, not something to rely on. Also check any record keyed by an enum, because Zod 4 now requires every enum key to be present; switch those to `z.partialRecord` where keys are optional.
- Keeps single-argument z.record(z.string()) calls in Zod 4 code because they still run.
- Assumes an enum-keyed z.record makes every key optional in Zod 4.
- Believes a z.tuple silently ignores items beyond its fixed positions.
- Expects .nonempty() in Zod 4 to change the inferred type to a non-empty tuple.
- Treats z.record and z.object as interchangeable for unknown keys.
Assumes Zod 4; z.record's API now takes a key and a value schema, enum-keyed records are exhaustive (z.partialRecord restores optional keys), and .nonempty() no longer changes the inferred array type.