Skip to content

Commit 5280816

Browse files
committed
Improve disc union error messaging
1 parent 69ccb67 commit 5280816

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/zod/src/v4/core/schemas.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1972,6 +1972,7 @@ export const $ZodDiscriminatedUnion: core.$constructor<$ZodDiscriminatedUnion> =
19721972
const propValues: util.PropValues = {};
19731973
for (const option of def.options) {
19741974
const pv = option._zod.propValues;
1975+
console.dir(pv, { depth: null });
19751976
if (!pv || Object.keys(pv).length === 0)
19761977
throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
19771978
for (const [k, v] of Object.entries(pv!)) {
@@ -1989,6 +1990,8 @@ export const $ZodDiscriminatedUnion: core.$constructor<$ZodDiscriminatedUnion> =
19891990
const map: Map<util.Primitive, $ZodType> = new Map();
19901991
for (const o of opts) {
19911992
const values = o._zod.propValues[def.discriminator];
1993+
if (!values || values.size === 0)
1994+
throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
19921995
for (const v of values) {
19931996
if (map.has(v)) {
19941997
throw new Error(`Duplicate discriminator value "${String(v)}"`);

play.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
11
import { z } from "zod/v4";
22

3-
z;
3+
// z;
4+
import { discriminatedUnion, literal, object, pipe, string, transform } from "zod/v4-mini";
5+
6+
const schemaWithPipe = discriminatedUnion("type", [
7+
object({
8+
type: pipe(
9+
transform((v) => v),
10+
literal("a")
11+
),
12+
a: string(),
13+
}),
14+
object({
15+
type: pipe(
16+
transform((v) => v),
17+
literal("b")
18+
),
19+
b: string(),
20+
}),
21+
]);
22+
23+
schemaWithPipe.safeParse({ type: "a", a: "abc" });

0 commit comments

Comments
 (0)