8000 V4: `discriminatedUnion` cannot parse valid input as it did in v3 · Issue #4399 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

V4: discriminatedUnion cannot parse valid input as it did in v3 #4399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
hibanka opened this issue May 18, 2025 · 1 comment
Closed

V4: discriminatedUnion cannot parse valid input as it did in v3 #4399

hibanka opened this issue May 18, 2025 · 1 comment

Comments

@hibanka
Copy link
hibanka commented May 18, 2025

Zod version: zod@3.25.0-beta.20250518T002810

import { z } from 'zod/v4';

const schema = z.object({
  topLevel: z.discriminatedUnion([
    z.object({
      topLevelDiscKey: z.literal('fruit'),
      lowLevel: z.discriminatedUnion([
        z.object({
          lowLevelDiscKey: z.literal('apple'),
          someKey: z.literal('1$'),
        }),
        z.object({
          lowLevelDiscKey: z.literal('banana'),
          someKey: z.number(),
        }),
      ]),
    }),
  ]),
});

// Works.
const firstDiscUnion = schema.parse({
  topLevel: { topLevelDiscKey: 'fruit', lowLevel: { lowLevelDiscKey: 'apple', someKey: '1$' } },
} satisfies z.infer<typeof schema>);
console.info(firstDiscUnion);

// Does not work.
// Throws 'No matching discriminator' error.
// However, this code works in zod v3 (for v3 schema needed to be slightly modified to explicitly specify the discriminator).
const secondDiscUnion = schema.parse({
  topLevel: { topLevelDiscKey: 'fruit', lowLevel: { lowLevelDiscKey: 'banana', someKey: 2 } },
} satisfies z.infer<typeof schema>);
console.info(secondDiscUnion);
@colinhacks
Copy link
Owner

Okay clearly my supposedly clever implementation of discriminated unions isn't cutting it. I've reverted the "no-discriminator" API which significantly simplifies the implementation. I've confirmed the code above works. #4392

Thanks for these issues, really glad this was discovered before the stable release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
0