Sub topic 9
Unions and discriminated unions
This chapter assumes you know TypeScript union types (string | number), narrowing with if or switch, and the Zod basics from earlier chapters: z.object, z.infer, and safeParse. Real data often has more than one valid shape. A message may carry a string or a number, and an event may be a click or a key press. Zod models these cases with unions.
Plain unions with z.union
z.union takes an array of schemas. A value is valid if it matches at least one of them.
import { z } from "zod";
const Id = z.union([z.string().min(1), z.number().int().positive()]);
type Id = z.infer<typeof Id>; // string | number
console.log(Id.parse("abc")); // "abc"
console.log(Id.parse(42)); // 42
console.log(Id.safeParse(-3).success); // false
console.log(Id.safeParse(true).success); // falseTwo shorthands do the same thing:
z.string().or(z.number())builds a union from a method call..nullable()is a union of the original schema withnull.
Use whichever reads best. The inferred type is the same.
How Zod evaluates a union
Zod tries the options in the order you list them. It returns the result of the first option that succeeds. If none succeed, the parse fails with an issue whose code is "invalid_union".
Since the diagram must be in a diagram fence, here is the evaluation flow:
This order has a consequence for object schemas. By default, z.object strips keys it does not know. If an earlier option matches a subset of the input, Zod stops there and drops the extra keys.
import { z } from "zod";
const Circle = z.object({ radius: z.number() });
const Ring = z.object({ radius: z.number(), hole: z.number() });
const Wrong = z.union([Circle, Ring]);
const Right = z.union([Ring, Circle]);
console.log(Wrong.parse({ radius: 5, hole: 2 })); // { radius: 5 }
console.log(Right.parse({ radius: 5, hole: 2 })); // { radius: 5, hole: 2 }
console.log(Right.parse({ radius: 5 })); // { radius: 5 }Wrong silently loses hole. List the most specific schemas first, or avoid the problem with a discriminated union.
The problem with plain unions of objects
Plain unions have two more drawbacks when the options are objects.
- Zod may have to test every option, so large unions are slower.
- The error is vague. When no option matches, Zod reports that the union failed. It does not tell you which option you probably meant.
Most tagged data has a field whose value names the variant. Examples are type, kind, or status. If you tell Zod about that field, it can pick the right schema directly.
z.discriminatedUnion
A discriminated union takes the name of the discriminator field and an array of object schemas. Each object must declare that field with a literal value (or an enum of literals).
import { z } from "zod";
const Event = z.discriminatedUnion("type", [
z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
z.object({ type: z.literal("key"), key: z.string() }),
]);
type Event = z.infer<typeof Event>;
function describe(e: Event): string {
return e.type === "click" ? `click at ${e.x},${e.y}` : `key ${e.key}`;
}
console.log(describe(Event.parse({ type: "click", x: 10, y: 20 })));
console.log(describe(Event.parse({ type: "key", key: "Enter" })));Zod reads type from the input and runs only the matching schema. Failures are then specific. If type is "click" but x is a string, the issue points at x for the click schema. It does not describe a mismatch against the whole union.
The inferred type is a TypeScript discriminated union, so narrowing works in if, switch, and ternaries, as shown in describe.
Reading discriminated union errors
Inspect error.issues the same way as for any schema.
import { z } from "zod";
const Event = z.discriminatedUnion("type", [
z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
z.object({ type: z.literal("key"), key: z.string() }),
]);
const inputs: unknown[] = [
{ type: "click", x: "10", y: 20 },
{ type: "scroll" },
{ x: 1, y: 2 },
];
for (const input of inputs) {
const result = Event.safeParse(input);
if (!result.success) {
for (const issue of result.error.issues) {
console.error(issue.code, issue.path.join("."), issue.message);
}
}
}The first input fails inside the click schema, so the issue path is x. The second has an unknown tag value. The third has no tag at all. For those two, Zod reports an issue about the discriminator. The path points at type, or is empty in some versions when the field is missing. The code and message text differ between Zod 3 and Zod 4, so print issue.code while you develop and avoid matching on message strings in application logic.
Exhaustive handling with switch
Because the output type is a real discriminated union, the compiler can check that you handled every variant. Assign the leftover value to never in the default branch.
import { z } from "zod";
const Shape = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("circle"), radius: z.number().positive() }),
z.object({ kind: z.literal("rect"), width: z.number(), height: z.number() }),
]);
type Shape = z.infer<typeof Shape>;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rect":
return shape.width * shape.height;
default: {
const unreachable: never = shape;
return unreachable;
}
}
}
console.log(area(Shape.parse({ kind: "rect", width: 3, height: 4 }))); // 12If you later add a third variant to the schema, area stops compiling until you handle it. The schema change and the code change stay in step.
Rules and limits of discriminated unions
- Literal discriminators. The discriminator on each option must be a literal or an enum of literals. You cannot use
z.string()as the tag. - Unique values. Two options must not share a discriminator value. Zod reports overlapping values when you create the schema.
- Object options. Each option must be an object schema. In Zod 3, an option wrapped in
.refine()or.transform()is no longer a plain object schema and cannot be used directly. Zod 4 relaxes some of this. Check your installed version, or apply the refinement to the whole union instead. - Multiple values per variant. An option can accept several tag values with
z.enum(["a", "b"])when your Zod version supports it. Otherwise, define two options that share a base schema (see the composition chapter). - Plain union still has uses. Use
z.unionwhen the options are not objects, when there is no shared tag, or when the tag differs between options.
| Situation | Use |
|---|---|
| `string` or `number` | `z.union` |
| Value or `null` | `.nullable()` |
| Objects with a shared literal tag field | `z.discriminatedUnion` |
| Objects with no tag field | `z.union`, most specific first |
| Many variants and fast, clear errors | `z.discriminatedUnion` |
Unions at the boundaries
Discriminated unions fit data that comes from outside your program, such as webhook payloads, message queue events, and API responses with a status field.
import { z } from "zod";
const ApiResponse = z.discriminatedUnion("status", [
z.object({ status: z.literal("ok"), data: z.array(z.string()) }),
z.object({ status: z.literal("error"), message: z.string() }),
]);
async function load(url: string): Promise<string[]> {
const res = await fetch(url);
const parsed = ApiResponse.safeParse(await res.json());
if (!parsed.success) {
throw new Error("Unexpected response shape");
}
if (parsed.data.status === "error") {
throw new Error(parsed.data.message);
}
return parsed.data.data;
}The res.json() call returns any, but after safeParse the value has a precise type. Every later branch is checked by the compiler.
A union can also combine coercion with a fallback. z.union([z.coerce.number(), z.string()]) turns "5" into 5, and leaves "abc" alone because Number("abc") is NaN, which Zod rejects. Be careful with this pattern. Coercion accepts many inputs, so a coercing option placed first can claim values you wanted another option to handle.
Common mistakes
- Listing a broad object schema before a narrower one in
z.union, so extra keys are stripped. - Using
z.string()for a discriminator instead ofz.literalorz.enum. - Matching on
issue.messagetext, which changes between Zod versions. - Forgetting that
.optional()on the discriminator makes the tag missing-able, which defeats discrimination. - Treating an
invalid_unionissue as a precise error. Its nested details may contain the real cause.
Exercise
A schema is z.union([z.object({ id: z.number() }), z.object({ id: z.number(), name: z.string() })]). Parsing { id: 1, name: "Ada" } returns { id: 1 }. Why does that happen, and what are two ways to fix it?
Show answer
Zod tries union options in order and returns the first success. The first object schema accepts the input, and because z.object strips unknown keys, name is dropped. Fix it by listing the more specific schema (the one with name) first. Alternatively, add a literal tag field such as kind to both objects and use z.discriminatedUnion, so Zod chooses the schema by tag.
Exercise
Define a discriminated union named Notification with the tag field channel. A variant with channel "email" has a to field (string), and a variant with channel "sms" has a phone field (string). Then write a function that returns the contact string for either variant without using a type assertion.
Show answer
const Notification = z.discriminatedUnion("channel", [z.object({ channel: z.literal("email"), to: z.string() }), z.object({ channel: z.literal("sms"), phone: z.string() })]); type Notification = z.infer<typeof Notification>; function contact(n: Notification): string { return n.channel === "email" ? n.to : n.phone; } Checking n.channel narrows the type, so each branch can read its own field safely.