Alternative primitive inputs
A field legitimately accepts multiple primitive types, such as an identifier supplied as either text or a number.
Zod · Type Alias
ZodUnion is Zod’s schema type for logical OR validation. It accepts an input when any member schema succeeds, testing members in order and returning the first successful parsed value.
ZodUnion represents a logical OR between multiple schemas. The union tries its options in declaration order and returns the first successfully parsed value; if none match, parsing fails with issues from the attempted options.
z.union([schemaA, schemaB, ...])| Name | Type | Description |
|---|---|---|
options | ZodType[] | An array of schemas representing the alternatives in the union. |
A Zod union schema whose inferred output is the union of the member schemas' outputs.
z.union.import { z } from "zod";
const stringOrNumber = z.union([z.string(), z.number()]);
console.log(stringOrNumber.parse("hello"));
console.log(stringOrNumber.parse(42));Creates a schema accepting either a string or a number, then parses one value of each kind.
A field legitimately accepts multiple primitive types, such as an identifier supplied as either text or a number.
A payload can have one of several shapes and no shared discriminator is available.
A recursive JSON-like value may be a primitive, array, or record.
A union models a logical OR, such as string or number. Create one with z.union([z.string(), z.number()]), and Zod checks the options in order until one succeeds.
Follow-up: How can parsing be made more efficient for object variants? Use z.discriminatedUnion() with a shared discriminator key so Zod can choose the relevant option directly.
Zod tests the input against each option in declaration order. It returns the first value that validates successfully; if every option fails, parsing fails.
Follow-up: Why can branch order matter? If multiple schemas accept the same input, the first successful schema determines the parsed result and any transformations it applies.
A discriminated union is composed of object schemas sharing a key such as status. Zod reads that discriminator to select one option, which is generally faster and produces errors for the selected option.
Follow-up: When is a regular union still appropriate? Use it when variants do not share a suitable discriminator or when the union is small and straightforward.
z.unionz.discriminatedUnionZodDiscriminatedUnionz.orz.infer