Sub topic 8
Arrays, tuples, records, and enums
This chapter assumes you can define object schemas with z.object, call safeParse, and read error.issues. You also need to know how TypeScript represents arrays, tuples, Record, and string literal unions. Here you will learn the four Zod schemas for collections and fixed sets of values, how each one fails, and when to choose one over another.
Choosing a collection schema
Real payloads rarely consist of a single object. They contain lists of items, fixed-size pairs, dictionaries with unknown keys, and fields limited to a few allowed strings. Each of these has a matching Zod schema.
Arrays
z.array(schema) accepts a JavaScript array in which every element passes the inner schema. The inferred type is T[].
import { z } from "zod";
const Tags = z.array(z.string().min(1)).min(1).max(5);
type Tags = z.infer<typeof Tags>; // string[]
const result = Tags.safeParse(["a", "", "c"]);
if (!result.success) {
for (const issue of result.error.issues) {
console.error(JSON.stringify(issue.path), issue.message);
}
}The empty string at index 1 fails, and the issue's path is [1]. Zod validates every element and reports every failure, so a list with three bad items produces three issues. When the array sits inside an object, the path continues from the parent, for example ["tags", 1]. Join the path with . or format it yourself to get readable messages.
The array-level checks are .min(n), .max(n), .length(n), and .nonempty(). They run on the array itself, independent of its elements.
Two details matter in practice:
.nonempty()also changes the inferred type to[T, ...T[]]. That tuple type tells the compiler that index 0 exists, so you can readlist[0]without an undefined check.z.arrayrejects anything that is not an array, including array-like objects andSet. Convert before parsing if your source produces those.
Tuples
A tuple is a fixed-length array where each position has its own type. Use z.tuple for data such as coordinates, [key, value] pairs, or CSV rows of known layout.
import { z } from "zod";
const Point = z.tuple([z.number(), z.number()]);
type Point = z.infer<typeof Point>; // [number, number]
console.log(Point.safeParse([1, 2]).success); // true
console.log(Point.safeParse([1, 2, 3]).success); // false: too many items
console.log(Point.safeParse([1]).success); // false: too few items
const Row = z.tuple([z.string(), z.number()]).rest(z.boolean());
type Row = z.infer<typeof Row>; // [string, number, ...boolean[]]
console.log(Row.safeParse(["a", 1, true, false]).success); // trueBy default a tuple must match its length exactly. .rest(schema) allows extra trailing items that all share one type, and the inferred type gains a matching rest element.
Tuples are a poor fit for JSON that you design yourself. An object with named fields is easier to read, easier to extend, and produces clearer error paths. Choose a tuple when the format is dictated by someone else or by a compact encoding.
Records
z.record(keySchema, valueSchema) describes a dictionary: an object whose keys are not known in advance but whose values share one type. Typical examples are a map of user IDs to scores or a set of HTTP headers.
import { z } from "zod";
const Scores = z.record(z.string(), z.number().int().nonnegative());
type Scores = z.infer<typeof Scores>; // Record<string, number>
const parsed = Scores.parse({ alice: 10, bob: 7 });
console.log(Object.entries(parsed));
const bad = Scores.safeParse({ alice: 10, bob: -1 });
if (!bad.success) {
console.error(JSON.stringify(bad.error.issues[0].path)); // ["bob"]
}Every value is validated, and the failing key becomes the last element of the issue path. The key schema validates the key strings too. A restrictive key schema gives you format checks on the keys:
import { z } from "zod";
const ById = z.record(z.string().regex(/^user_\d+$/), z.string());
console.log(ById.safeParse({ user_1: "Ada" }).success); // true
console.log(ById.safeParse({ admin: "Ada" }).success); // falseKeep these points in mind:
- Object keys are always strings at runtime, even when you write numeric keys.
z.record(z.number(), ...)is rarely what you want. If you need numeric keys, validate them as strings and convert afterwards. - A record with a fixed set of keys, such as an enum, behaves differently across Zod versions. In Zod 3 the result is a partial object, so missing keys are allowed. In Zod 4 every key in the enum is required, and
z.partialRecordgives the old behavior. Check which version you use before relying on this. - Use
z.objectwhen you know the keys. A record says "any keys", and a typo in a key name will not be caught.
Enums
z.enum accepts one string from a closed list. The inferred type is the union of those literals, the same as a TypeScript string literal union.
import { z } from "zod";
const Role = z.enum(["admin", "editor", "viewer"]);
type Role = z.infer<typeof Role>; // "admin" | "editor" | "viewer"
console.log(Role.options); // ["admin", "editor", "viewer"]
console.log(Role.enum.admin); // "admin"
const result = Role.safeParse("owner");
if (!result.success) {
console.error(result.error.issues[0].message);
}The schema exposes its values in two ways. .options is the array of allowed strings, which you can use to build a dropdown or a help message. .enum is an object that maps each value to itself, so you can write Role.enum.admin and get autocomplete and a compile error if the value is removed later.
Pass the list as a literal array. If you build it in a separate variable, TypeScript widens it to string[] and the inferred type collapses to string. Add as const to the variable in that case:
import { z } from "zod";
const levels = ["debug", "info", "warn", "error"] as const;
const LogLevel = z.enum(levels);
type LogLevel = z.infer<typeof LogLevel>; // "debug" | "info" | "warn" | "error"Defining the array once and using it for both the schema and other code, such as a CLI help text, keeps the allowed values in a single place.
Enums versus unions of literals
z.enum only works with strings. For numbers or mixed values, use z.union of z.literal schemas:
import { z } from "zod";
const Priority = z.union([z.literal(1), z.literal(2), z.literal(3)]);
type Priority = z.infer<typeof Priority>; // 1 | 2 | 3If your code already uses a TypeScript enum, Zod has a way to accept it, but the call depends on the version: z.nativeEnum in Zod 3, and z.enum itself in Zod 4. Prefer string literal unions for new code, because they need no runtime object and serialize to JSON without surprises.
Combining the schemas
These schemas nest freely. The following payload schema uses all four in one object.
import { z } from "zod";
const Team = z.object({
name: z.string().min(1),
members: z
.array(
z.object({
name: z.string().min(1),
role: z.enum(["admin", "editor", "viewer"]),
}),
)
.nonempty(),
office: z.tuple([z.number(), z.number()]),
quotas: z.record(z.string(), z.number().int()),
});
type Team = z.infer<typeof Team>;
const input = {
name: "Platform",
members: [
{ name: "Ada", role: "admin" },
{ name: "Lin", role: "owner" },
],
office: [52.5, 13.4],
quotas: { builds: 100, deploys: "ten" },
};
const result = Team.safeParse(input);
if (!result.success) {
for (const issue of result.error.issues) {
console.error(issue.path.join("."), "-", issue.message);
}
}This reports two issues. One has the path members.1.role because "owner" is not in the enum. The other has the path quotas.deploys because "ten" is not a number. The indexes and keys in the path tell you exactly which element failed, which is the information you need to build field-level error messages in a form or an API response.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Enum type is `string` | The values array was widened | Use a literal array or add `as const` |
| Tuple rejects a longer array | Tuples are exact by default | Add `.rest(schema)` or use `z.array` |
| `list[0]` may be undefined | Plain `z.array` allows empty arrays | Use `.nonempty()` for the tuple-typed result |
| Numeric record keys fail | Object keys are strings at runtime | Validate keys as strings, then convert |
| Typo in a key is accepted | A record allows any key | Use `z.object` when keys are known |
Exercise
Write a schema for the object { "sizes": ["S", "M", "L"], "stock": { "S": 4, "M": 0 } }, where sizes is a non-empty list drawn from S, M, and L, and stock maps size names to non-negative integers. Which inferred type does sizes have, and what path does Zod report for { "sizes": ["XL"], "stock": {} }?
Show answer
Use z.object({ sizes: z.array(z.enum(["S", "M", "L"])).nonempty(), stock: z.record(z.string(), z.number().int().nonnegative()) }). The sizes field has the type ["S" | "M" | "L", ...("S" | "M" | "L")[]] because of .nonempty(). For the failing input, Zod reports one issue with the path ["sizes", 0], because the element at index 0 is not in the enum. An empty stock object is valid.