In Zod 4, how do you derive create, update and public response schemas from one user schema using pick, omit, partial and extend?
answer
- one base shape, several views
- mask objects with true
- partial is shallow
- defaults survive optional in v4
- object-level refine blocks reshaping
basics
~20 sKeep one base z.object and derive views from it: omit server-owned fields for create, pick the editable fields then call .partial() for update, omit secrets for the response. Use .extend() rather than the deprecated .merge(), and watch defaults and object-level refinements.
solid answer
~40 sStart from one `User` object and derive each view with mask objects: `User.omit({ id: true, passwordHash: true, role: true }).extend({ password: z.string().min(12) })` for create, `User.pick({ email: true, name: true }).partial()` for a patch, `User.omit({ passwordHash: true })` for the response, whose strip mode drops the hash when you parse outgoing data. Three Zod 4 traps matter. A field with `.default()` still fills in under `.partial()`, so a patch that omits `role` comes back with `role: "member"` and can overwrite stored data. `.pick()`, `.omit()` and `.partial()` throw at schema build time if the object carries its own `.refine()`. A mask that names a key the shape lacks is a type error and a runtime `Error`. To combine schemas, use `.extend(B.shape)` or spread both shapes into a new builder; `.merge()` is deprecated in Zod 4.
code
typescript · 24 linesimport * as z from "zod";
const User = z.object({
id: z.uuid(),
email: z.email(),
name: z.string().min(1),
passwordHash: z.string(),
role: z.enum(["member", "admin"]).default("member"),
});
const CreateUser = User.omit({ id: true, passwordHash: true, role: true })
.extend({ password: z.string().min(12) });
const UpdateUser = User.pick({ email: true, name: true }).partial();
const PublicUser = User.omit({ passwordHash: true });
// The trap: .partial() keeps the default on role
const RiskyPatch = User.omit({ id: true, passwordHash: true }).partial();
console.log(RiskyPatch.parse({ name: "Ada" }));
// { name: "Ada", role: "member" }
console.log(UpdateUser.parse({ name: "Ada" }));
// { name: "Ada" }go deeper
Recall the four methods and their mask syntax: pick and omit take an object of keys set to true, partial makes keys optional, extend adds keys.
Walk through deriving create, update and response views from one base, in the right order: pick or omit first, then partial, then extend.
Name the production traps: defaults reapplied by a partial patch, object-level refinements that make reshaping throw, and derived schemas inheriting the base's unknown-key mode.
Argue for one base schema per entity as the team's source of truth, and set the rule for where defaults and cross-field refinements live so every view stays derivable.
## Why derive instead of redeclaring A typical resource needs several **views** of one entity: the body a client sends to create it, the partial body sent to update it, and the body returned to callers. Redeclaring each by hand drifts the moment someone adds a field to one and forgets the others. Zod object schemas expose reshaping methods that return **new schemas** and never modify the original, so one base schema can feed every view. ## The reshaping methods | Method | What it returns | Typical use | |---|---|---| | `.pick({ k: true })` | only the masked keys | the editable subset | | `.omit({ k: true })` | every key except the masked ones | drop server-owned or secret fields | | `.partial()` / `.partial({ k: true })` | all or some keys wrapped in optional | update and patch bodies | | `.required()` / `.required({ k: true })` | all or some keys made non-optional | the reverse of partial | | `.extend({ ... })` | the shape plus new or overriding keys | add create-only fields such as `password` | Every one of them keeps the base schema's **unknown-key mode**, so deriving from a `z.strictObject` gives strict views. The masks are objects whose values are `true`, not arrays of key names. ## A worked derivation Take a base user with `id`, `email`, `name`, `passwordHash` and a `role` that defaults to `"member"`: 1. **Create:** `User.omit({ id: true, passwordHash: true, role: true }).extend({ password: z.string().min(12) })`. The server owns `id`, `passwordHash` and `role`, and the client supplies a plain password instead. 2. **Update:** `User.pick({ email: true, name: true }).partial()`. Pick the fields a user may edit first, then make them optional, so a patch can carry any subset. 3. **Response:** `User.omit({ passwordHash: true })`. Because the derived object strips unknown keys, parsing a database row with it removes the hash from what you send back. The order of calls matters for readability more than for correctness. Picking the editable fields first and then calling `.partial()` states the editable surface once; calling `.partial()` on the whole base and omitting afterwards makes it easy to forget a server-owned field. A masked `.partial({ name: true })` makes only the named keys optional, which suits a replace-style update where most fields stay required. ## The traps - **Defaults inside optional fields still apply.** In Zod 4, an optional field that wraps a `.default()` fills in the default when the key is absent. `.partial()` produces exactly that wrapping, so `User.omit({ id: true, passwordHash: true }).partial().parse({ name: "Ada" })` returns `{ name: "Ada", role: "member" }`. A patch handler that writes every parsed key silently demotes an admin. Pick only fields without defaults into the patch schema, or keep defaults out of the base shape and add them in the create schema with `.extend()`. - **Object-level refinements block reshaping.** A `.refine()` attached to the whole object (a rule spanning several fields) makes `.pick()`, `.omit()` and `.partial()` throw an `Error` when the derived schema is built, because the refinement was written against the original shape. `.extend()` throws only when it would overwrite an existing key of a refined object; `.safeExtend()` allows that override, and TypeScript checks that the new field's type is assignable to the old one. The usual fix is to keep the base shape unrefined, derive from it, and attach the rule to each derived schema that needs it. - **Masks are checked.** Naming a key the shape does not have, say `omit({ pasword: true })`, is a TypeScript error and also throws at runtime with `Unrecognized key`. - **`.partial()` is shallow.** It makes the top-level keys optional; a nested `address` object keeps its own required keys. ## Combining schemas: extend, spread, merge Zod 4 deprecates `A.merge(B)`. The replacements: - `A.extend(B.shape)` adds B's keys to A, with B winning on shared keys, and keeps **A's** unknown-key mode. `.merge()` instead took the second schema's catchall, which made the result's strictness depend on argument order. - `z.object({ ...A.shape, ...B.shape })` builds a fresh object, makes the chosen mode visible at the call site (swap in `z.strictObject` or `z.looseObject`), and is the cheapest form for the TypeScript compiler. The docs note that chained `.extend()` calls get quadratically more expensive to type-check on large schemas. - Avoid `z.intersection(A, B)` for objects: it returns an intersection schema that lacks `.pick()`, `.omit()` and the other object methods. The static types of each view follow automatically from the schema; how `z.infer` and its input and output variants read them is a separate subject.
- Your Zod 4 base user schema has an object-level .refine. What happens when you call .omit on it, and how do you restructure?Building the derived schema throws an `Error` saying `.omit()` cannot be used on object schemas containing refinements, and `.pick()` and `.partial()` behave the same. Keep an unrefined base object, derive every view from it, and attach the cross-field rule to each derived schema that still has the fields it reads.
- Why does Zod 4 steer you from A.merge(B) to A.extend(B.shape) or spread syntax?`.merge()` is deprecated. It took the second schema's unknown-key handling, so the result's strictness depended on argument order. `.extend()` keeps the first schema's mode, and spreading both shapes into `z.object`, `z.strictObject` or `z.looseObject` states the mode at the call site and type-checks fastest.
- How do you stop a Zod 4 patch schema from writing defaults the client never sent?Derive the patch only from fields without defaults, for example `pick({ email: true, name: true }).partial()`. Alternatively keep `.default()` out of the base shape and add the defaulted fields in the create schema with `.extend()`, so the update view never inherits them.
- Thinks .partial() on a field with .default() leaves the key absent when the client omits it.
- Assumes .pick() and .omit() work on an object schema carrying its own object-level refine.
- Reaches for A.merge(B) as the Zod 4 way to combine two object schemas.
- Believes .partial() also makes the fields of nested objects optional.
- Expects .omit() with a misspelt key to be silently ignored at runtime.
- Uses z.intersection for object schemas and then expects .pick() on the result.
Assumes Zod 4; .merge() is deprecated in favour of .extend(B.shape) or spread, and Zod 4 applies defaults inside optional fields, which Zod 3 did not.