Skip to content

Docs: “no shared discriminator key → init error” statement is inaccurate in v4 beta #4332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
bufferings opened this issue May 7, 2025 · 0 comments

Comments

@bufferings
Copy link

Hi 👋

While trying the v4 beta I noticed that the docs for z.discriminatedUnion() don’t match the current behavior.

https://v4.zod.dev/v4#upgraded-zdiscriminatedunion

If no shared discriminator key is found, Zod will throw an error at schema initialization time.

What actually happens

  • Each option only needs at least one discriminator field.
  • The discriminator keys do not have to be shared across options.
  • Zod throws at init time only when an option has zero discriminator fields, not when keys differ.
import { z } from 'zod';

// ✅ Works – different keys but each option has a literal
z.discriminatedUnion([
  z.object({ kind: z.literal('square'), size: z.number() }),
  z.object({ name: z.literal('rectangle'), width: z.number(), height: z.number() }),
]);

// ❌ Fails – second option lacks any literal / enum field
z.discriminatedUnion([
  z.object({ kind: z.literal('square'), size: z.number() }),
  z.object({ name: z.string(), width: z.number(), height: z.number() }), // ← error
]);
// Error: Invalid discriminated union option at index "1"

Checked with [email protected].

Suggested wording

If any option lacks a discriminator key, Zod will throw an error at schema initialization time.

Thanks,

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

No branches or pull requests

1 participant