Skip to content
New issue

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

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

Already on GitHub? # to your account

fix(v3): dirty union bug #3727

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions src/__tests__/unions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,29 @@ test("return valid over invalid", () => {
});
});

test("return dirty result over aborted", () => {
test("union with dirty result", () => {
const result = z
.union([z.number(), z.string().refine(() => false)])
.safeParse("a");
expect(result.success).toEqual(false);
if (!result.success) {
expect(result.error.issues).toEqual([
expect(result.error.issues).toMatchObject([
{
code: "custom",
message: "Invalid input",
path: [],
code: "invalid_union",
unionErrors: [
expect.objectContaining({
code: "invalid_type",
expected: "number",
received: "string",
path: [],
message: "Expected number, received string",
}),
expect.objectContaining({
code: "custom",
message: "Invalid input",
path: [],
}),
],
},
]);
}
Expand Down
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
Loading