Capítulo 15 de 61
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).
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.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">
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.strictObject where correctness matters more than leniency..catchall() is the right tool when unknown keys are expected but must still conform to a type (e.g. arbitrary string metadata)..keyof() turns an object schema's keys into a reusable enum schema, useful for building key-based lookups or discriminants..extend(), .pick(), .omit(), .partial() for deriving new object schemas from existing ones.