Array and Object Schemas
What you'll learn: How to use Zod's z.array() and z.object() to validate complex nested data structures.
Now that you've learned primitive schemas, optional fields, and defaults, you're ready to validate collections and structured data—the heart of most API responses and form data.
Arrays with z.array()
Arrays are validated by wrapping a schema for their elements:
import { z } from 'zod';
const numberListSchema = z.array(z.number());
const result = numberListSchema.safeParse([1, 2, 3]);
// ✅ success: true, data: [1, 2, 3]
const failure = numberListSchema.safeParse([1, "two", 3]);
// ❌ success: false (string not allowed)
Arrays can contain any schema—primitives, objects, even other arrays.
Objects with z.object()
Objects are defined by specifying each property's schema:
const userSchema = z.object({
name: z.string(),
age: z.number(),
isActive: z.boolean().optional()
});
type User = z.infer<typeof userSchema>;
// { name: string; age: number; isActive?: boolean }
Composing Complex Shapes
The power emerges when you nest these structures:
const teamSchema = z.object({
teamName: z.string(),
members: z.array(
z.object({
name: z.string(),
role: z.string(),
skills: z.array(z.string())
})
),
founded: z.number()
});
const data = {
teamName: "Engineering",
members: [
{ name: "Alice", role: "Lead", skills: ["TypeScript", "Node"] },
{ name: "Bob", role: "Dev", skills: ["React"] }
],
founded: 2020
};
teamSchema.parse(data); // ✅ Validated!
Zod validates every level: the team object, the members array, each member object, and each skills array.
Key Takeaway: Use z.array() for collections and z.object() for structured data—nest them freely to mirror your API's shape with full type safety.