Build a specialized schema
Add fields to a reusable base object schema.
Zod · Module
.extend() creates a new object schema by adding fields to an existing object schema. Duplicate keys are overwritten by the supplied shape.
.extend() creates a new object schema by combining an existing object schema with the supplied shape. New keys are added, while keys shared with the original schema are replaced by the supplied schemas; use .safeExtend() instead when refinements or assignability checks matter.
objectSchema.extend(shape)| Name | Type | Description |
|---|---|---|
shape | object shape | An object shape containing fields to add or replace. |
A new object schema containing the original shape and the supplied shape, with supplied schemas overriding duplicate keys.
.extend() on an object schema and pass a shape containing the additional properties..safeExtend() when replacing properties must remain type-compatible with the base schema..extend() is the documented alternative to intersections..extend() can replace existing fields, so use it carefully when the shapes share property names..safeExtend() rather than .extend()..extend() to an intersection when combining object schemas, because the result remains an object schema with object-specific methods.import { z } from "zod";
const User = z.object({
name: z.string(),
});
const Admin = User.extend({
role: z.literal("admin"),
});
console.log(Admin.parse({ name: "Ada", role: "admin" }));Creates a new object schema containing the original field and the added role field.
Add fields to a reusable base object schema.
Replace a property schema while deriving a related object schema.
Compose object schemas while retaining object methods such as pick and omit.
Define a complete shape when the resulting strictness should be immediately visible.
.extend() do?.extend() takes an object shape and returns a new object schema containing the original fields plus the supplied fields. If both schemas define a key, the supplied schema wins.
Follow-up: What should be used when the base schema has refinements? Use .safeExtend(), which is intended for refined schemas and enforces assignability for overwritten properties.
When keys overlap, the schema passed to .extend() overrides the corresponding schema in the base object. This makes replacement possible but can unintentionally weaken or change validation.
Follow-up: How can you avoid accidental overrides? Build a new object with spread syntax so the complete shape and strictness choice are explicit.
.extend() over an intersection for object schemas?.extend() returns a new object schema, while z.intersection() returns a ZodIntersection. The object returned by .extend() therefore retains object methods such as pick and omit.
Follow-up: When might spread syntax be preferable? It can make the resulting strictness level visually obvious while defining the complete object schema.
safeExtendobject spread syntaxz.intersectionpickomit