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

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay