DEV Community

Jen C.
Jen C.

Posted on

Using Zod's z.union: An Important Pitfall to Avoid

When using the schema z.union([z.object({}), anotherSchema.partial()]);, Zod checks if the object matches the empty object {} first.

Since an empty object can always be valid, Zod might decide that the object matches {} and stops there, ignoring the other options in the union.

To fix this, you should ensure that Zod prioritizes the more specific schema (anotherSchema.partial()) over the empty object. You can achieve this by reversing the order in the union.

For example:

import { z } from "zod";

// Define two schemas
const emptySchema = z.object({});
const anotherSchema = z.object({
  name: z.string(),
  age: z.number().optional(),
});

// Create a union where the empty schema is checked first
const problematicSchema = z.union([emptySchema, anotherSchema.partial()]);

// Test with an object that should match `anotherSchema.partial()`
const data = { name: "myName" };

const result = problematicSchema.safeParse(data);
console.log(result);

Enter fullscreen mode Exit fullscreen mode

The output is


{
  success: true,
  data: {}
}
Enter fullscreen mode Exit fullscreen mode

Instead of

{
  success: true,
  data: { name: "myName" }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)