Union and Discriminated Union Schemas
You'll learn how to validate data that can take one of several distinct shapes using Zod's union and discriminated union schemas.
What Are Union Schemas?
Sometimes your data can be one type or another—like a configuration value that accepts either a string or a number. In Zod, z.union() lets you define a schema that validates against multiple possibilities:
const idSchema = z.union([z.string(), z.number()]);
idSchema.parse("abc-123"); // ✓ Valid
idSchema.parse(42); // ✓ Valid
idSchema.parse(true); // ✗ Throws error
Think of it like a multiple-choice validator: the value must match at least one of the provided schemas.
What Are Discriminated Unions?
When your data can be one of several object shapes that share a common "tag" field, use z.discriminatedUnion(). This is more efficient and provides better error messages than regular unions:
const responseSchema = z.discriminatedUnion("status", [
z.object({ status: z.literal("success"), data: z.string() }),
z.object({ status: z.literal("error"), message: z.string() })
]);
responseSchema.parse({ status: "success", data: "Hello" }); // ✓
responseSchema.parse({ status: "error", message: "Oops" }); // ✓
The first argument ("status") is the discriminator key—Zod immediately checks that field to determine which schema to validate against, making it faster and clearer when validation fails.
When to Use Each
Use union for simple "either/or" types. Use discriminated union when handling objects with a common identifier field (like type, kind, or status) that determines their structure—common in state machines, API responses, and event handling.
Key Takeaway: Use z.union() for simple alternatives and z.discriminatedUnion() for tagged object variants, giving you type-safe handling of multiple data shapes at runtime.