Sub topic 10
Reusing schemas with extend, pick, omit, and partial
This chapter assumes you can define object schemas with z.object, derive types with z.infer, and call parse and safeParse. It also assumes you know TypeScript's own utility types such as Pick and Partial. Zod offers runtime counterparts of those utilities. They build new schemas from an existing one, so a change to the base schema reaches every shape derived from it.
Why derive schemas instead of copying them
Most applications need several related shapes of the same entity:
- A full record, as stored in the database.
- A create payload, without the server-generated
id. - An update payload, where every field is optional.
- A public view, without internal fields.
If you write each as a separate z.object, the rules drift apart. One copy gets min(1) on name and another does not. Deriving the variants from one base schema keeps a single source of truth, in the same way z.infer keeps the type and schema together.
The examples below use this base schema:
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
});
type User = z.infer<typeof User>;The four basic operations
Each method returns a new schema. The original is never modified, so it is safe to derive several variants from the same base.
| Method | What it does | Typical use |
|---|---|---|
| `pick` | Keeps only the listed keys | Narrow input for one operation |
| `omit` | Removes the listed keys | Hide server-generated or internal fields |
| `partial` | Makes keys optional | Update (patch) payloads |
| `extend` | Adds keys, or replaces existing ones | Add fields to a base shape |
pick and omit
Both take an object whose keys are the field names and whose values are true. Passing a key that does not exist in the schema is a TypeScript error, which catches typos at compile time.
import { z } from "zod";
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
});
const CreateUser = User.omit({ id: true });
const UserName = User.pick({ name: true });
type CreateUser = z.infer<typeof CreateUser>;
// { name: string; nickname?: string | undefined }
console.log(CreateUser.safeParse({ name: "Ada" }).success); // true
console.log(UserName.safeParse({ nickname: "A" }).success); // falseThe field schemas are carried over unchanged. CreateUser still requires name to be a non-empty string.
Use omit when the set of fields to keep is large and the set to remove is small, and pick in the opposite case. The choice matters when the base schema later gains a field. A schema built with omit includes the new field automatically. A schema built with pick does not. Pick the behavior you want for new fields.
partial
partial() makes every field optional. This suits a PATCH request, where the client sends only the fields it wants to change.
const UpdateUser = User.pick({ name: true, nickname: true }).partial();
type UpdateUser = z.infer<typeof UpdateUser>;
// { name?: string | undefined; nickname?: string | undefined }
console.log(UpdateUser.parse({})); // {}
console.log(UpdateUser.parse({ nickname: "Ace" })); // { nickname: 'Ace' }Optional does not mean unchecked. A field that is present is still validated against its original rule:
const result = UpdateUser.safeParse({ name: "" });
console.log(result.success); // false, because name must still have at least 1 characterTo make only some fields optional, pass a mask in the same style as pick:
const PartialName = User.partial({ name: true });
// id is still required, name is now optionalextend
extend takes an object of new field schemas and returns a schema that has both the old and the new fields.
const WithEmail = User.extend({ email: z.string().min(3) });
type WithEmail = z.infer<typeof WithEmail>;
// { id: number; name: string; email: string; nickname?: string | undefined }If a key already exists, the new definition replaces the old one. This lets you tighten or relax a single field:
const StrictUser = User.extend({
name: z.string().min(3).max(40),
});Chaining operations
Because every method returns a schema, you can chain them to describe a shape in one expression. Read the chain from left to right.
const PublicProfile = User.omit({ id: true })
.extend({ joinedAt: z.coerce.date() })
.partial({ nickname: true });Keep chains short. Beyond three steps, give the intermediate result a name so a reader can see what shape it has.
Combining two schemas
When you want the fields of two separate schemas rather than one base plus a few fields, spread the shape property of one into z.object, or pass its shape to extend.
const Timestamps = z.object({
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
});
const Post = z.object({
id: z.number().int(),
title: z.string().min(1),
}).extend(Timestamps.shape);
type Post = z.infer<typeof Post>;
// { id: number; title: string; createdAt: Date; updatedAt: Date }merge and .and() (intersection) also exist, but extend with .shape is easier to reason about. Intersections produce more complicated inferred types and weaker error messages. Prefer extend when you can.
The flow of derived schemas
All the variants below come from one definition. Editing the base changes each variant in the same step.
Gotchas and edge cases
Refinements are lost or restricted
A schema that carries an object-level refine is no longer a plain object schema. In Zod 3 it becomes a ZodEffects, which has no pick, omit, partial, or extend. Zod 4 changed this, and its rules are stricter: using pick or omit on an object that has refinements throws an error. Whichever version you use, the portable approach is to derive first and refine last:
const Signup = z
.object({
password: z.string().min(8),
confirm: z.string(),
})
.refine((data) => data.password === data.confirm, {
message: "Passwords do not match",
path: ["confirm"],
});
// Wrong order: calling pick or extend on Signup may fail or drop the rule.
// Better: keep the plain object, derive from it, then refine each result.
const SignupFields = z.object({
password: z.string().min(8),
confirm: z.string(),
});
const SignupWithName = SignupFields.extend({ name: z.string().min(1) }).refine(
(data) => data.password === data.confirm,
{ message: "Passwords do not match", path: ["confirm"] },
);Define the plain object once, export it, and apply refine at each point of use.
partial does not remove defaults or transforms
partial() wraps each field in an optional. A field with .default(...) still receives its default when the key is missing. For update payloads this can silently overwrite stored data with defaults. If you build a patch schema from a schema with defaults, check what an empty object parses to:
const Settings = z.object({
theme: z.enum(["light", "dark"]).default("light"),
pageSize: z.number().int().default(20),
});
console.log(Settings.partial().parse({}));
// Zod 3: {}
// Zod 4: { theme: 'light', pageSize: 20 }Because the output differs between versions, test this case for your installation. If you want a patch schema that never applies defaults, define it from a base schema that has no defaults.
Unknown keys
By default, z.object removes keys it does not know about. extend, pick, omit, and partial keep that behavior. If the base schema was made with .strict() or .passthrough(), the derived schema keeps that mode in most cases, but verify with a test when it matters.
Deep partial
partial() affects only the top level. Nested objects keep their required fields. Zod 3 had deepPartial() but marked it deprecated, and it does not exist in Zod 4. If you need a nested patch, define the nested schema's partial form explicitly:
const Profile = z.object({
name: z.string(),
address: z.object({ city: z.string(), zip: z.string() }),
});
const ProfilePatch = Profile.extend({
address: Profile.shape.address.partial(),
}).partial();Choosing between approaches
- Use
omitorpickpluspartialwhen the variant is a strict subset of the base. - Use
extendwhen the variant adds or tightens fields. - Use a separate
z.objectwhen two shapes only look alike today but will change for different reasons. Shared code is not always better. A create payload and a database row often evolve independently.
Exercise
Given const Product = z.object({ id: z.number(), title: z.string().min(1), price: z.number().positive() }), write a schema ProductPatch for a PATCH request that allows title and price to be omitted but forbids changing id. What does ProductPatch.safeParse({ price: -5 }).success return, and why?
Show answer
const ProductPatch = Product.omit({ id: true }).partial();. The call returns false. partial makes price optional, but when it is present it is still checked by positive(), and -5 fails that rule.
Exercise
You wrote Signup.pick({ password: true }) where Signup is a z.object followed by .refine(...), and it fails. What is the fix?
Show answer
Keep the plain z.object in its own constant, derive the variants from it with pick, omit, extend, or partial, and call .refine(...) on each derived schema at its point of use. The refinement turns the object into a different kind of schema that does not support these methods in the same way.