Sub topic 8
Arrays, Tuples, Records, and Enums
Assume you know basic TypeScript types, JavaScript arrays and objects, JSON, npm imports, and how to handle exceptions. This chapter focuses on Zod schemas for collections and fixed sets of values. These schemas validate runtime data and can also produce matching TypeScript types.
Arrays: repeated values with one shape
An array schema checks every element against the same schema. Use z.array(itemSchema) when the length can vary and each item follows one rule.
import { z } from "zod";
const Scores = z.array(z.number().int().min(0).max(100));
const result = Scores.safeParse([80, 95, 72]);
if (result.success) {
const total = result.data.reduce((sum, score) => sum + score, 0);
console.log(total);
} else {
console.error(result.error.issues);
}Scores rejects values such as [80, "95"] because the second element is not a number. You can add array-level rules such as .min(1), .max(10), or .length(3):
const Tags = z.array(z.string().min(1)).min(1).max(5);The item rule and the array rule produce different errors. An invalid item has a path containing its index, such as [1]. An invalid array length has a path for the array itself.
Tuples: fixed positions and lengths
A tuple is an array with a known number of positions. Each position can have a different type.
const Coordinate = z.tuple([
z.number(),
z.number(),
]);
type Coordinate = z.infer<typeof Coordinate>;
// [number, number]
const point = Coordinate.parse([12.5, -4]);The schema rejects [12.5], [12.5, -4, 9], and ["12.5", -4]. Use a tuple when position has meaning, such as [latitude, longitude] or [statusCode, message]. Use an object instead when named fields make the data easier to understand.
Records: dynamic keys with consistent values
A record validates an object whose keys are not known in advance but whose values share one schema.
const FeatureFlags = z.record(
z.string(),
z.boolean(),
);
type FeatureFlags = z.infer<typeof FeatureFlags>;
// Record<string, boolean>
const flags = FeatureFlags.parse({
darkMode: true,
compactLayout: false,
});This accepts any string keys, but every value must be a boolean. If keys also need a rule, provide a key schema:
const ScoresByUser = z.record(
z.string().min(1),
z.number().int().nonnegative(),
);Use z.object for a known set of named properties. Use z.record for maps, dictionaries, and configuration entries that can grow.
Enums: a closed set of values
An enum schema accepts only the listed values. With string values, z.enum works well with TypeScript inference.
const OrderStatus = z.enum([
"pending",
"paid",
"shipped",
"cancelled",
]);
type OrderStatus = z.infer<typeof OrderStatus>;
// "pending" | "paid" | "shipped" | "cancelled"
const status = OrderStatus.parse("paid");An enum is stricter than z.string(). It prevents unsupported states from entering the rest of the application.
| Data shape | Zod schema | Typical use |
|---|---|---|
| Variable-length values of one kind | `z.array(item)` | Tags or scores |
| Fixed positions | `z.tuple([...])` | Coordinates |
| Unknown keys, consistent values | `z.record(key, value)` | Feature flags |
| One of several exact values | `z.enum([...])` | Status fields |
Exercise
Which schema should validate an object containing arbitrary language codes mapped to translated labels, such as { en: "Hello", fr: "Bonjour" }?
Show answer
Use z.record(z.string(), z.string()), because the keys are dynamic and every value is a string.