Skip to main content

How to Validate One of Several JSON Shapes with a Zod Discriminated Union

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

Some JSON values come in more than one shape, with one field that says which: an order with "method": "pickup" names a store, and one with "method": "delivery" names an address. Zod's z.discriminatedUnion validates exactly that: it reads the field first, then checks the shape it points to, and tells you precisely what's wrong.

Syntax​

Syntax
const <Schema> = z.discriminatedUnion("<key>", [
z.object({ <key>: z.literal("<value 1>"), <the fields of shape 1> }),
z.object({ <key>: z.literal("<value 2>"), <the fields of shape 2> }),
]);

const <result> = <Schema>.safeParse(<value>);
PartWhat it is
"<key>"The field that says which shape a value has. Zod's documentation calls it the discriminator
z.object({ … })One shape. Every shape has the key, with its own value
z.literal("<value 1>")The exact value of the key for this shape
safeParse(<value>)Checks a value without throwing. <result>.success says whether it passed; <result>.data holds the value, and <result>.error the problems

Zod's documentation explains why not a plain z.union(): regular unions check the input against each option in order and return the first one that passes, while a discriminated union uses a discriminator key to make parsing more efficient.

The Example​

A small script checks five orders. An order is picked up at a store or delivered to an address, and its method says which. Two orders are fine, one has a field that doesn't belong, one misses its address, and one has a method that doesn't exist.

Prerequisites​

  • Node.js 22.18 or later, so that node runs a TypeScript file directly. node --version shows yours; I used Node.js 26.

Step 1: Create the Project​

Terminal
mkdir order-check
cd order-check
npm init -y
npm pkg set type=module
npm install zod@4.6.7 --save-exact

npm init -y creates package.json, and npm pkg set type=module lets the script use import. zod@4.6.7 is the newest version of Zod, and --save-exact records exactly that version.

Step 2: Describe the Shapes​

Create orders.ts:

orders.ts
import { z } from "zod";

// An order is picked up at a store or delivered to an address. The field
// "method" says which, and each method has its own fields.
const Order = z.discriminatedUnion("method", [
z.object({ method: z.literal("pickup"), store: z.string() }),
z.object({ method: z.literal("delivery"), address: z.string() }),
]);

type Order = z.infer<typeof Order>;

const orders: unknown[] = [
{ method: "pickup", store: "Downtown" },
{ method: "delivery", address: "12 Lake Road" },
{ method: "delivery", address: "12 Lake Road", store: "Downtown" },
{ method: "delivery", store: "Downtown" },
{ method: "drone" },
];

for (const body of orders) {
const result = Order.safeParse(body);
if (result.success) {
console.log(`Valid: ${describe(result.data)}`);
} else {
console.log(`Invalid: ${JSON.stringify(body)}`);
console.log(z.prettifyError(result.error));
}
}

// After the check, TypeScript knows which fields each method has.
function describe(order: Order) {
return order.method === "pickup"
? `pick up at ${order.store}`
: `deliver to ${order.address}`;
}
  • Order is the union: the key is method, and each shape gives it a literal value and its own field.
  • z.infer<typeof Order> turns the schema into a TypeScript type, so describe gets the type the check produced.
  • z.prettifyError turns the problems into text, one line per problem. Zod's documentation: it provides a human-readable string representation of the error.
  • describe shows the point of a discriminated union in TypeScript: after order.method === "pickup", TypeScript knows order.store exists, and in the other branch, order.address.

Node.js runs this file as it is: since version 22.18 it removes the TypeScript types before running, without checking them. Your editor, or the TypeScript compiler, does the checking.

Step 3: Run It​

Terminal
node orders.ts
Output
Valid: pick up at Downtown
Valid: deliver to 12 Lake Road
Valid: deliver to 12 Lake Road
Invalid: {"method":"delivery","store":"Downtown"}
✖ Invalid input: expected string, received undefined
→ at address
Invalid: {"method":"drone"}
✖ Invalid discriminator value. Expected 'pickup' | 'delivery'
→ at method
  • The first two orders are valid.
  • The third, a delivery with an extra store field, is valid too. z.object doesn't mind unknown fields: Zod's documentation says unrecognized keys are stripped from the parsed result, so result.data simply doesn't have it.
  • The fourth is a delivery without an address. Zod checked it against the delivery shape, because its method said so, and names the missing field: → at address.
  • The fifth has a method that no shape has, and the message lists the ones that exist.

Step 4: Refuse Fields That Don't Belong​

A delivery that names a store is suspicious: maybe the sender mixed up the two shapes. To refuse anything that isn't in the shape, use z.strictObject instead of z.object, which Zod describes as a strict schema that throws an error when unknown keys are found. The final orders.ts:

orders.ts
import { z } from "zod";

// An order is picked up at a store or delivered to an address. The field
// "method" says which, and each method has its own fields.
const Order = z.discriminatedUnion("method", [
z.strictObject({ method: z.literal("pickup"), store: z.string() }),
z.strictObject({ method: z.literal("delivery"), address: z.string() }),
]);

type Order = z.infer<typeof Order>;

const orders: unknown[] = [
{ method: "pickup", store: "Downtown" },
{ method: "delivery", address: "12 Lake Road" },
{ method: "delivery", address: "12 Lake Road", store: "Downtown" },
{ method: "delivery", store: "Downtown" },
{ method: "drone" },
];

for (const body of orders) {
const result = Order.safeParse(body);
if (result.success) {
console.log(`Valid: ${describe(result.data)}`);
} else {
console.log(`Invalid: ${JSON.stringify(body)}`);
console.log(z.prettifyError(result.error));
}
}

// After the check, TypeScript knows which fields each method has.
function describe(order: Order) {
return order.method === "pickup"
? `pick up at ${order.store}`
: `deliver to ${order.address}`;
}

The only change is z.strictObject, twice. Run it again:

Terminal
node orders.ts
Output
Valid: pick up at Downtown
Valid: deliver to 12 Lake Road
Invalid: {"method":"delivery","address":"12 Lake Road","store":"Downtown"}
✖ Unrecognized key: "store"
Invalid: {"method":"delivery","store":"Downtown"}
✖ Unrecognized key: "store"
✖ Invalid input: expected string, received undefined
→ at address
Invalid: {"method":"drone"}
✖ Invalid discriminator value. Expected 'pickup' | 'delivery'
→ at method

macOS-style terminal window titled Terminal — order-check showing two valid orders, the delivery with an extra store field refused with Unrecognized key: "store", the delivery without an address refused with Unrecognized key: "store" and Invalid input: expected string, received undefined at address, and the drone order refused with Invalid discriminator value. Expected 'pickup' | 'delivery' at method

The delivery with an extra store is now refused: Unrecognized key: "store". The one without an address gets both problems at once.

The Complete File​

macOS-style code window titled orders.ts showing the Order schema, a z.discriminatedUnion on method with two z.strictObject shapes, pickup with a store and delivery with an address, the list of five orders, the loop that prints Valid or Invalid with z.prettifyError, and the describe function that narrows on order.method

orders.ts from Step 4 is the whole program.

Common Mistakes​

MistakeWhat happensDo this instead
Using z.union for shapes with a type fieldZod tries every shape in order, and can't tell you which one the value meantUse z.discriminatedUnion with that field
Writing the key as z.string() instead of a literalThe key can't tell the shapes apartGive each shape z.literal("<its value>")
Expecting z.object to refuse extra fieldsThey pass, and are left out of result.dataUse z.strictObject
Using parse on input you don't controlA bad value throwsUse safeParse and check success

FAQ​

Can the key be something other than a string?​

Yes. Zod's documentation lists z.enum(), z.literal(), z.null(), or z.undefined() as the usual values, and a literal can be a number, such as z.literal(400).

Does the order of the shapes matter?​

Not for which shape is checked: the key picks it. That is the difference from z.union, which tries the shapes in order.

Conclusion​

When a value's shape depends on one of its fields, describe each shape with z.object and a z.literal for that field, and combine them with z.discriminatedUnion("<field>", [...]). safeParse then checks the shape the field points to, and z.prettifyError says what's wrong in plain lines. Use z.strictObject for shapes that should refuse unknown fields.

Additional Resources​