DEV Community

Jen C.
Jen C.

Posted on

3

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay