Skip to content

fix: union containing z.undefined() should be optional-in for object keys - #6044

Closed
sapirbaruch wants to merge 1 commit into
colinhacks:mainfrom
sapirbaruch:fix/union-undefined-optin
Closed

sapirbaruch wants to merge 1 commit into
colinhacks:mainfrom
sapirbaruch:fix/union-undefined-optin

Conversation

@sapirbaruch

Copy link
Copy Markdown

Ran into this via the discord.js bug report in #5993 — after digging in I traced it to a change in 4.4.0 (commit b6066b3, PR #5661) that stripped optin/optout off $ZodUndefined.

The problem:

z.object decides whether a missing key is valid by checking el._zod.optin === "optional". Before 4.4, z.undefined() set that flag, so a union like:

z.union([z.never(), z.array(z.never()), z.undefined()])

was treated as optional-in and a missing key would silently coerce to undefined (which the union accepts). After the change, neither z.undefined() nor the union propagate that flag, so the object bails early with "expected nonoptional" before the schema even runs.

The fix:

In $ZodUnion's lazy optin/optout computation, also check whether any option's _zod.values set includes undefined. z.undefined() has values = new Set([undefined]), so a union with a z.undefined() member now correctly inherits the optional-in/out behavior.

// before
def.options.some((o) => o._zod.optin === "optional")

// after
def.options.some((o) => o._zod.optin === "optional" || o._zod.values?.has(undefined))

This is intentionally conservative: the new check only fires when a member's static value set contains undefined, which is exactly when the union will accept a missing key.

Repro:

const schema = z.object({
  autocomplete: z.literal(true),
  choices: z.union([z.never(), z.never().array(), z.undefined()]),
});

schema.parse({ autocomplete: true });        // 4.3.x: ok — 4.4.x: throws nonoptional
schema.parse({ autocomplete: true, choices: undefined });  // ok in both

The updated snapshot in optional.test.ts (line ~144) reflects the corrected behavior: only the z.undefined() standalone field still requires an explicit key; a union containing z.undefined() does not.

Refs #5993.

When a z.union() has z.undefined() as one of its options, the union
accepts undefined as a valid value. In object schemas, z.object checks
el._zod.optin === "optional" to decide whether a missing key is allowed.
Before this fix, a union containing z.undefined() did not propagate the
optin/optout flags, so { choices: z.union([z.never(), z.array(z.never()), z.undefined()]) }
would throw "expected nonoptional, received undefined" for missing keys
even though the union can parse undefined just fine.

The fix: in the $ZodUnion constructor, extend the optin/optout lazy
check to also match options whose _zod.values set includes undefined
(which is how z.undefined() signals it accepts undefined).

Fixes colinhacks#5993

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — Restores 4.3.x optional-in behavior for unions containing z.undefined() as an object key, fixing the regression introduced in 4.4.0.

  • packages/zod/src/v4/core/schemas.ts — Adds o._zod.values?.has(undefined) to $ZodUnion's lazy optin/optout computation so unions with a z.undefined() member correctly propagate the optional flag.
  • packages/zod/src/v4/classic/tests/never-union-object.test.ts — New regression test covering the exact discord.js scenario from #5993.
  • packages/zod/src/v4/classic/tests/optional.test.ts — Updates snapshot and assertions to reflect the restored behavior.

Pullfrog  | View workflow run | Using Kimi K2 | 𝕏

@wahajahmed010 wahajahmed010 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch and clean fix, @sapirbaruch! The root cause analysis is spot-on — PR #5661 cleaned up optin/optout from $ZodUndefined, but the union propagation needed to catch undefined through the values set instead. The fix is conservative and correct.

What I like:

  • Clear reproduction path from discord.js downstream
  • The optional chaining on _zod.values handles schemas that do not define a values set (e.g., ZodString, ZodNumber) gracefully
  • Test coverage is thorough — covers all 4 states (explicit undefined, empty array, populated array, missing key)

One thought for completeness:
The tests cover a single-depth union in an object. Worth also adding a nested union test: a z.union inside another z.union with z.undefined(). The lazy chain should propagate optin correctly, but locking it in with a test would prevent regression. Not a blocker.

Excellent first contribution! 🦌

@colinhacks

Copy link
Copy Markdown
Owner

Closing this — the 4.4.0 behavior is intentional. z.undefined() was marked optional on the input side, which propagated through unions and let a required key go missing; the inferred type never agreed, so that was an unintentional soundness hole. 4.4.0 dropped the flag, as a bug fix in a minor.

Append .optional() to the union if you want the key to be omittable. Thanks for the repro 👍

@colinhacks colinhacks closed this Aug 13, 2026

This branch was successfully deployed

1 active deployment
Preview – zod-v4 — 6c04c19b Deployed May 31, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants