Sub topic 9
Unions and Discriminated Unions
Assume you know basic TypeScript types, JavaScript objects, JSON, npm imports, and try/catch. In this chapter, you will describe values that may have more than one valid shape.
A union means a value can match one of several types. TypeScript writes a union with |:
type Id = string | number;This tells the compiler that Id may be a string or a number. A Zod union performs the matching at runtime too. This matters for data from an API, form, file, or user. TypeScript cannot check data after the program has been compiled.
Basic unions
Use z.union when each option has a different type or when no single field identifies the option.
import { z } from "zod";
const Id = z.union([z.string().min(1), z.number().int().positive()]);
type Id = z.infer<typeof Id>;
console.log(Id.parse("user-42")); // "user-42"
console.log(Id.parse(42)); // 42
const result = Id.safeParse(false);
if (!result.success) {
console.error(result.error.issues);
}Zod tries the member schemas until one succeeds. If every member fails, the result is invalid. Keep union members distinct when possible. Overlapping schemas can make the accepted result depend on their order, which makes behavior harder to understand.
A union of object schemas is useful when different objects represent different cases:
const ClickEvent = z.object({
type: z.literal("click"),
x: z.number(),
y: z.number(),
});
const KeyEvent = z.object({
type: z.literal("key"),
key: z.string().min(1),
});
const Event = z.union([ClickEvent, KeyEvent]);The z.literal checks that a value equals one exact value. Here, type separates the two event shapes.
Discriminated unions
A discriminated union is a union whose objects share a field with different literal values. That field is the discriminator. Use z.discriminatedUnion when every option has the same discriminator key.
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(event: Event): string {
if (event.type === "click") {
return `click at ${event.x},${event.y}`;
}
return `key ${event.key}`;
}
console.log(describe({ type: "click", x: 10, y: 20 }));
console.log(describe({ type: "key", key: "Enter" }));The same type check narrows the inferred TypeScript type. Inside the click branch, x and y are available. Inside the key branch, key is available. TypeScript can also report an error if you forget a required property.
Choosing between the two
Use z.union for unrelated shapes or unions without a shared discriminator. Use z.discriminatedUnion for tagged object variants. The discriminated form makes the intended cases clearer and can produce more focused validation behavior.
When adding a new variant, update the schema first. Then let z.infer and TypeScript errors show where application code must handle that case.
Exercise
What happens when an object has type "click" but its x field is missing?
Show answer
The discriminated union selects the click schema, then validation fails because x is required.