zod icon indicating copy to clipboard operation
zod copied to clipboard

fix(v3): dirty union bug

Open mmkal opened this issue 5 months ago • 1 comments

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.

mmkal avatar Aug 26 '24 15:08 mmkal