colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

fix(v3): dirty union bug #3727

Open mmkal opened 3 weeks ago

mmkal commented 3 weeks ago

bug repro: https://stackblitz.com/edit/stackblitz-starters-swdj3e?file=index.test.js&startScript=test

Basically, zod v3 wrongly reports a "normal" error rather than a union error for a union of strict objects (and presumably other unions that set status=dirty:

import { test, expect } from 'vitest';
import { z } from 'zod';

test('hmm', () => {
  const union = z.union([
    z.object({ x: z.number() }).strict(),
    z.object({ y: z.number() }).strict(),
  ]);

  expect(union.safeParse({ x: 1, y: 1 })).toMatchInlineSnapshot(`
    {
      "error": [ZodError: [
      {
        "code": "unrecognized_keys",
        "keys": [
          "y"
        ],
        "path": [],
        "message": "Unrecognized key(s) in object: 'y'"
      }
    ]],
      "success": false,
    }
  `);
  expect(union.safeParse({ x: 1, y: 1 })).toMatchObject({
    success: false,
    error: {
      issues: [
        {
          code: 'invalid_union',
          unionErrors: [expect.any(z.ZodError), expect.any(z.ZodError)],
        },
      ],
    },
  });
});

Note: this does not repro in v4. I'm not sure if there's anything going into zod v3 still but opening this against main in hopes that it can get fixed in v3.

netlify[bot] commented 3 weeks ago

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit 3b3af1942e23078b055089251e34828f2c7baae9
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/66ce259bc951de0008a45670
Deploy Preview https://deploy-preview-3727--guileless-rolypoly-866f8a.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.