Capítulo 15 de 61

Chapter 15: Objects — Definition, Strictness & Shape

Core Idea

z.object() defines a shape of required-by-default properties, with three strictness modes for handling keys not in the shape: strip (default), reject (strictObject), or pass through (looseObject).

Key Concepts

  • z.object({...}): all properties required by default; unrecognized keys in the input are silently stripped from the parsed result.
  • z.strictObject({...}): throws if the input has any key not in the shape.
  • z.looseObject({...}): unrecognized keys pass through unchanged into the parsed result.
  • .catchall(schema): instead of stripping/rejecting/passing-through unknown keys as-is, validates each of them against a given schema.
  • .shape: accesses the individual field schemas (Dog.shape.name); in Zod Mini, Dog.def.shape.name.
  • .keyof(): derives a ZodEnum schema of the object's own key names.

Code Examples

const Person = z.object({ name: z.string(), age: z.number() });
// all properties required by default

const Dog = z.object({ name: z.string(), age: z.number().optional() });
Dog.parse({ name: "Yeller", extraKey: true });
// => { name: "Yeller" }  (extraKey stripped)

const StrictDog = z.strictObject({ name: z.string() });
StrictDog.parse({ name: "Yeller", extraKey: true }); // throws

const DogWithStrings = z
  .object({ name: z.string(), age: z.number().optional() })
  .catchall(z.string());
DogWithStrings.parse({ name: "Yeller", extraKey: "value" }); // ok
DogWithStrings.parse({ name: "Yeller", extraKey: 42 });      // throws

const keySchema = Dog.keyof(); // ZodEnum<"name" | "age">
  • What it demonstrates: the three unknown-key behaviors, and introspecting an object schema's shape/keys.

Anti-patterns

  • Relying on z.object()'s default strip behavior when you actually need validation: silently dropped keys can hide bugs (typos in field names go unnoticed) — use z.strictObject() in contexts (like config parsing) where an unexpected key should be an error.

Key Takeaways

  1. The default strip behavior is convenient for permissive APIs but can mask typos — reach for strictObject where correctness matters more than leniency.
  2. .catchall() is the right tool when unknown keys are expected but must still conform to a type (e.g. arbitrary string metadata).
  3. .keyof() turns an object schema's keys into a reusable enum schema, useful for building key-based lookups or discriminants.

Connects To

  • Objects — Extending & Deriving: .extend(), .pick(), .omit(), .partial() for deriving new object schemas from existing ones.
  • Records: for a dictionary of arbitrary keys all validated against one value schema, rather than a fixed shape with a catchall.