Skip to content

Commit

Permalink
fix: dirty union bug
Browse files Browse the repository at this point in the history
  • Loading branch information
mmkal committed Aug 26, 2024
1 parent 8552233 commit 83828f3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
20 changes: 20 additions & 0 deletions src/__tests__/unions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,23 @@ test("readonly union", async () => {
union.parse("asdf");
union.parse(12);
});

test("union of strict objects", async () => {
// ensure bug in 3.23.8 is fixed, where "dirty" parse failures would mean reporting the first error, rather than a proper `invalid_union` with `unionErrors`.
// Demo of bug: https://stackblitz.com/edit/stackblitz-starters-swdj3e?file=index.test.js&startScript=test
const union = z.union([
z.object({ x: z.number() }).strict(), //
z.object({ y: z.number() }).strict(),
]);
expect(union.safeParse({ x: 1, y: 1 })).toMatchObject({
success: false,
error: {
issues: [
{
code: "invalid_union",
unionErrors: [expect.any(z.ZodError), expect.any(z.ZodError)],
},
],
},
});
});
9 changes: 0 additions & 9 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2987,8 +2987,6 @@ export class ZodUnion<T extends ZodUnionOptions> extends ZodType<
})
).then(handleResults);
} else {
let dirty: undefined | { result: DIRTY<any>; ctx: ParseContext } =
undefined;
const issues: ZodIssue[][] = [];
for (const option of options) {
const childCtx: ParseContext = {
Expand All @@ -3007,20 +3005,13 @@ export class ZodUnion<T extends ZodUnionOptions> extends ZodType<

if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}

if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}

if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}

const unionErrors = issues.map((issues) => new ZodError(issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
Expand Down

0 comments on commit 83828f3

Please sign in to comment.