Union and Discriminated Union Schemas
You'll learn how to use Zod's z.union() and z.discriminatedUnion() to validate data that can be one of several distinct shapes.
When data from an API can be one of multiple shapes, you need runtime validation that matches TypeScript's union types. Zod provides two tools for this: basic unions and discriminated unions.
Basic Unions with z.union()
A union schema validates that incoming data matches at least one of several possible schemas:
import { z } from 'zod';
const stringOrNumber = z.union([z.string(), z.number()]);
stringOrNumber.parse("hello"); // ✓ valid
stringOrNumber.parse(42); // ✓ valid
stringOrNumber.parse(true); // ✗ throws error
type StringOrNumber = z.infer<typeof stringOrNumber>; // string | number
Think of unions like a security checkpoint with multiple valid ID types—you can show either a passport or a driver's license, and either one gets you through.
Discriminated Unions with z.discriminatedUnion()
For discriminated unions (unions with a common property that identifies the shape), Zod provides an optimized validator:
const successSchema = z.object({
status: z.literal("success"),
data: z.string()
});
const errorSchema = z.object({
status: z.literal("error"),
message: z.string()
});
const apiResponse = z.discriminatedUnion("status", [
successSchema,
errorSchema
]);
apiResponse.parse({ status: "success", data: "Done!" }); // ✓
apiResponse.parse({ status: "error", message: "Failed" }); // ✓
type ApiResponse = z.infer<typeof apiResponse>;
// { status: "success"; data: string } | { status: "error"; message: string }
The first argument ("status") is the discriminator property—Zod checks this field first to quickly determine which schema to validate against, making it more efficient than trying each union member sequentially.
Key Takeaway: Use z.union() when data can be one of several types, and z.discriminatedUnion() when those types share a common identifying property—this gives you type-safe runtime validation that mirrors TypeScript's compile-time union types.