Course contentsShow
← JavaScript
Lesson 2636 of 2,72353. Type Safety Without TypeScriptFree lesson

Object Schemas

Define schemas for objects with typed properties, and validate entire object structures.

Object Schemas

What you'll learn: How to define schemas for objects with typed properties and validate entire object structures using Zod.

Beyond Primitives

You've already learned how to define schemas for strings, numbers, and booleans. Real-world JavaScript, though, is full of objects — structured collections of properties. Object schemas let you describe the exact shape an object should have, including what properties it must contain and what type each property should be.

Think of an object schema like a blueprint for a building: it specifies every room (property) that must exist and what kind of room it is, ensuring nothing's missing or malformed.

Defining Object Schemas

In Zod, you create object schemas using z.object() and passing an object where each key maps to a schema:

import { z } from 'zod';

const userSchema = z.object({
  name: z.string(),
  age: z.number(),
  email: z.string()
});

This schema says: "A valid user must have a name (string), age (number), and email (string)."

Validating Entire Objects

Now you can validate entire object structures in one go:

const result = userSchema.safeParse({
  name: "Alice",
  age: 30,
  email: "alice@example.com"
});

console.log(result.success); // true

const bad = userSchema.safeParse({
  name: "Bob",
  age: "thirty" // wrong type
});

console.log(bad.success); // false

Each property is checked against its schema. If any property fails, the entire validation fails.

Key Takeaway: Object schemas define the complete structure of an object, validating all properties at once to ensure data integrity across complex structures.