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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more