Array and Tuple Schemas
You'll learn how to validate arrays of uniform types and fixed-length tuples with mixed types using Zod.
When working with runtime validation, you often need to ensure that arrays contain elements of a specific type, or that a fixed-length sequence has specific types at each position. Zod provides two distinct tools for these scenarios: array schemas and tuple schemas.
Array Schemas
An array schema validates that every element in an array matches a given type. Think of it like a container that can hold any number of items, but they must all be the same shape:
import { z } from 'zod';
const numberArray = z.array(z.number());
const stringArray = z.array(z.string());
numberArray.parse([1, 2, 3]); // ✓ Valid
stringArray.parse(['a', 'b']); // ✓ Valid
numberArray.parse([1, 'two', 3]); // ✗ Throws error
You can also nest arrays and apply constraints:
const userArray = z.array(z.object({
name: z.string(),
age: z.number()
}));
Tuple Schemas
A tuple schema validates a fixed-length array where each position has a specific type. It's like a form with numbered fields—position matters:
const coordinates = z.tuple([z.number(), z.number()]);
const userRecord = z.tuple([z.string(), z.number(), z.boolean()]);
coordinates.parse([10.5, 20.3]); // ✓ Valid
userRecord.parse(['Alice', 25, true]); // ✓ Valid
coordinates.parse([10.5, 20.3, 30]); // ✗ Wrong length
userRecord.parse([25, 'Alice', true]); // ✗ Wrong types at positions
Use arrays when you have a homogeneous collection of unknown length. Use tuples when you have a heterogeneous, fixed-length sequence where position indicates meaning.
Key Takeaway: Zod's z.array() validates collections of the same type, while z.tuple() validates fixed-length sequences with position-specific types—choose based on whether your data is homogeneous or heterogeneous.