skip to content

Your service receives event payloads that differ by a type field. In Zod 4, why choose z.discriminatedUnion over z.union, and how do the errors differ?

level: seniorimportance: should knowfreq 50%

answer

  1. try every option versus look up one
  2. first success wins
  3. issue path at the tag
  4. checked when the schema is built
  5. strip makes object options overlap

basics

~20 s

z.discriminatedUnion reads the type field and runs only the matching option, so errors land on that option's fields or on the type path. z.union tries options in order, keeps the first success and usually fails with one vague invalid_union issue.

solid answer

~50 s

`z.union([A, B, C])` runs each option in order and returns the first that passes. When none does, the result is typically one `invalid_union` issue with the default message `Invalid input`, holding every option's issues in its `errors` array, so the caller cannot tell which variant was meant. `z.discriminatedUnion("type", [...])` reads `input.type`, looks the option up in a map and runs only that one, so a refund event with a string `amount` fails with `invalid_type` at path `["amount"]`. An unknown tag gives one `invalid_union` issue at path `["type"]` with a message listing the expected values. The lookup also avoids a quiet bug: with strip mode, a plain union of overlapping object options can match the wrong variant first and drop the other variant's fields. Zod 4 also throws on configuration mistakes: a missing discriminator when the schema is built, a duplicated tag value on the first parse.

code

typescript · 19 lines
typescript
import * as z from "zod";

const OrderEvent = z.discriminatedUnion("type", [
  z.object({ type: z.literal("order.created"), orderId: z.string(), total: z.number() }),
  z.object({ type: z.literal("order.refunded"), orderId: z.string(), amount: z.number() }),
]);

const badAmount = OrderEvent.safeParse({ type: "order.refunded", orderId: "o1", amount: "12" });
if (!badAmount.success) {
  console.log(badAmount.error.issues.map((i) => [i.code, i.path]));
  // [["invalid_type", ["amount"]]]
}

const unknownType = OrderEvent.safeParse({ type: "order.shipped", orderId: "o1" });
if (!unknownType.success) {
  const issue = unknownType.error.issues[0];
  console.log(issue.path, issue.message);
  // ["type"] Invalid discriminator value. Expected 'order.created' | 'order.refunded'
}

go deeper

for a junior

Know that z.discriminatedUnion takes the tag field name first, then a list of object schemas that each declare a literal value for it.

for a middle

Explain the runtime difference: z.union tries options in order and keeps the first success, while the discriminated version looks up one option by its tag.

for a senior

Diagnose the vague invalid_union error and the silent field loss from overlapping stripped options, and fix both by keying payloads on a discriminator.

for a principal

Set the convention that every message or event type carries a literal tag, so new payload versions add a tag value instead of loosening existing schemas.

## The problem: payloads that share one envelope An event stream, a webhook endpoint or a message queue consumer often receives several payload shapes through one entry point: `order.created` carries a `total`, `order.refunded` carries an `amount`, and so on. Each payload carries a **discriminator**, a field such as `type` whose literal value says which shape the rest of the object has. Zod offers two ways to validate such input, and they behave very differently on failure. ## How z.union decides `z.union([A, B, C])` is a naive **or**: 1. It runs the input through each option in order. 2. It returns the **first** option that succeeds, without looking further. 3. If every option fails, it typically reports a single `invalid_union` issue at the union's own path, with the default message `Invalid input` and an `errors` array holding one issue list per option. That last step is the practical pain. A caller who sent an `order.refunded` event with a bad `amount` receives a generic failure, and the precise reason is buried among irrelevant complaints from the options they never meant. The second pain comes from **strip mode**. Plain object schemas drop unknown keys and still succeed, so object options overlap more than people expect. If option A is `{ orderId }` and option B is `{ orderId, amount }`, an input carrying both keys satisfies A first, and the parse returns `{ orderId }` with `amount` silently gone. ## How z.discriminatedUnion decides `z.discriminatedUnion("type", [Created, Refunded])` uses the discriminator instead of trial and error: - It reads `input.type` and looks up the one option that declares that value, through a map built from the options. - It runs **only** that option, so the issues you get are that option's issues at precise paths, for example `invalid_type` at `["amount"]`. - When the tag matches no option, it reports one `invalid_union` issue at path `["type"]` that lists the allowed values; the default English message reads `Invalid discriminator value. Expected 'order.created' | 'order.refunded'`. - A non-object input fails with an `invalid_type` issue expecting an object. The lookup map is built from each option's discriminator schema, so one option may claim several values. A tag declared as `z.enum(["order.created", "order.placed"])` sends both values to the same option, which is a clean way to keep accepting a legacy tag name while producers migrate to the new one. The docs present this as the efficient choice for larger unions, since the input is no longer run through every option. The inferred type is a TypeScript discriminated union, so `if (event.type === "order.refunded")` narrows it; how narrowing works belongs to the TypeScript material. ## What Zod 4 checks and allows | Concern | Zod 4 behaviour | |---|---| | An object option without the discriminator key | throws an `Error` when the schema is built | | Two options claiming the same discriminator value | throws `Duplicate discriminator value` on the first parse of an object, because the lookup map is built lazily; `safeParse` throws too instead of returning a failure | | Discriminator schemas | usually `z.literal()`, `z.enum()`, `z.null()` or `z.undefined()`, and also unions of literals or a pipe | | Nesting | a discriminated union can be an option of another, keyed on a different field | Because both mistakes throw an `Error` instead of producing a validation issue, a duplicated tag after a copy-paste is caught by any test that parses one sample object through the schema. ## Designing event schemas with it - Give every option a literal discriminator, and keep the shared envelope in one place by spreading a base shape (`...Envelope.shape`) or calling `.extend()` on a base object. - Prefer `z.discriminatedUnion` whenever the payloads carry a tag; reserve `z.union` for inputs with no common tag, such as a value that may be a string or a number. - When options genuinely lack a tag and must not overlap, make the narrower one a `z.strictObject` so it cannot match an input carrying the other's fields, or use `z.xor()`, which fails when more than one option matches. - Version event shapes by adding a new tag value rather than loosening an existing option, so old and new producers each map to exactly one schema. Turning the resulting issues into a response body or a log line is a separate formatting step and does not change which issues the union produces.

  • With z.union of two plain z.object options, why can a valid refund event come back missing its amount field?
    `z.union` returns the first option that succeeds. A plain object strips unknown keys, so an earlier option declaring only `orderId` accepts the refund input and returns it without `amount`. A discriminated union avoids this by choosing the option from the tag; without a tag, make the narrower option strict or order the options from most to least specific.
  • In Zod 4, what happens if two options of a z.discriminatedUnion declare the same literal for the discriminator?
    Zod builds the tag-to-option lookup lazily, so the first parse of any object throws an `Error` reading `Duplicate discriminator value`, whatever tag the input carries. Even `safeParse` throws rather than returning a failure, because this is a schema bug, not bad input. One test that parses a sample object catches it.

  • Thinks z.union picks the best-matching option rather than the first one that succeeds.
  • Expects a failed z.union to report the specific field error of the intended variant.
  • Believes a duplicated discriminator value is reported as a validation issue on matching payloads.
  • Assumes plain object options in a union cannot overlap because each declares different fields.
  • Says z.discriminatedUnion is only a type-level helper with the same runtime behaviour as z.union.

Assumes Zod 4; discriminated unions now accept union and pipe discriminators, can nest inside each other, and throw on an option without the key (at build time) or on duplicate tag values (on first parse).