Zod discriminatedUnion vs union
Warning
This post is more than a year old. Information may be outdated.
Definition
z.union([A, B, …])Generic union of unrelated schemas. (DEV Community).- z.discriminatedUnion("key", [A, B, …])
Union of object schemas that all contain the literal-valued propertykey`. (GitHub)
Input constraints
unionaccepts any Zod types (objects, primitives, arrays, effects).discriminatedUnionaccepts onlyZodObjects whosekeyfield is az.literal(...)unique to each branch.
Runtime algorithm
unioniterates through every branch until one succeeds; worst-case O(n) full validation of every branch.discriminatedUnionreads the discriminator value once, selects the matching branch, validates only that branch; constant-time dispatch, faster on large unions. (DEV Community)
Backlinks1
250516Comments