Skip to content

Commit 45fdeda

Browse files
colinhacksdeepshekhardasclaude
authored
fix(v4): refine optin into a three-rung ladder, retire the fallback payload flag (#6419)
`optin` was overloaded across two readers asking different questions. $ZodObject/$ZodTuple asked "may this slot be absent?"; $ZodOptional asked "should I invoke you on undefined and trust the result?". $ZodTransform and $ZodCatch set optin="optional" to satisfy the first, which made the second draw the wrong conclusion — and payload.fallback existed only to undo it. That undo was itself unsound: it marked every transform invocation, so a .default() between the transform and an outer .optional() had its value discarded. Refine the value instead of adding a sibling: undefined required "optional" the container may omit it; nothing is supplied "defaulted" the container may omit it AND this schema substitutes "May the slot be absent?" becomes `!== undefined`. $ZodOptional asks the stronger question and tests `=== "defaulted"`, running the inner only when something down there actually answers the absence. payload.fallback is removed entirely. A restoration rather than an invention: `_zod.optionality` carried these same three values until #4405 split the axis into optin/optout and collapsed the ladder as collateral, pre-4.0.0. BREAKING (internals): `optin` is now "defaulted" rather than "optional" for default/prefault. Introspection that tests `optin === "optional"` should test `optin !== undefined`. z.input/z.output inference is unaffected. Closes #6321. Supersedes #6329. Co-authored-by: deepshekhardas <deepshekhardas@gmail.com> Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent e03d858 commit 45fdeda

9 files changed

Lines changed: 313 additions & 135 deletions

File tree

‎packages/zod/src/v4/classic/schemas.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2210,12 +2210,10 @@ export const ZodTransform: core.$constructor<ZodTransform> = /*@__PURE__*/ core.
22102210
if (output instanceof Promise) {
22112211
return output.then((output) => {
22122212
payload.value = output;
2213-
payload.fallback = true;
22142213
return payload;
22152214
});
22162215
}
22172216
payload.value = output;
2218-
payload.fallback = true;
22192217
return payload;
22202218
};
22212219
}

‎packages/zod/src/v4/classic/tests/lazy.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ test("opt passthrough", () => {
4242
expect(z.lazy(() => z.string().optional())._zod.optin).toEqual("optional");
4343
expect(z.lazy(() => z.string().optional())._zod.optout).toEqual("optional");
4444

45-
expect(z.lazy(() => z.string().default("asdf"))._zod.optin).toEqual("optional");
45+
expect(z.lazy(() => z.string().default("asdf"))._zod.optin).toEqual("defaulted");
4646
expect(z.lazy(() => z.string().default("asdf"))._zod.optout).toEqual(undefined);
4747
});
4848

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
import { expect, expectTypeOf, test } from "vitest";
2+
import { z } from "zod/v4";
3+
4+
/* ------------------------------------------------------------------ *
5+
* TYPE-LEVEL — the dangerous half. Defaults must stay OPTIONAL in
6+
* z.input and REQUIRED in z.output, exactly as before the ladder.
7+
* ------------------------------------------------------------------ */
8+
test("ladder: z.input / z.output unchanged by the extra rung", () => {
9+
const objDefault = z.object({ a: z.string().default("D"), b: z.number() });
10+
expectTypeOf<z.input<typeof objDefault>>().toEqualTypeOf<{ a?: string | undefined; b: number }>();
11+
expectTypeOf<z.output<typeof objDefault>>().toEqualTypeOf<{ a: string; b: number }>();
12+
13+
const objPrefault = z.object({ a: z.string().prefault("P"), b: z.number() });
14+
expectTypeOf<z.input<typeof objPrefault>>().toEqualTypeOf<{ a?: string | undefined; b: number }>();
15+
expectTypeOf<z.output<typeof objPrefault>>().toEqualTypeOf<{ a: string; b: number }>();
16+
17+
const objOptional = z.object({ a: z.string().optional() });
18+
expectTypeOf<z.input<typeof objOptional>>().toEqualTypeOf<{ a?: string | undefined }>();
19+
20+
const objTransform = z.object({
21+
a: z
22+
.string()
23+
.default("")
24+
.transform((v) => v.length),
25+
});
26+
expectTypeOf<z.input<typeof objTransform>>().toEqualTypeOf<{ a?: string | undefined }>();
27+
expectTypeOf<z.output<typeof objTransform>>().toEqualTypeOf<{ a: number }>();
28+
29+
const standalone = z.string().default("D");
30+
expectTypeOf<z.input<typeof standalone>>().toEqualTypeOf<string | undefined>();
31+
expectTypeOf<z.output<typeof standalone>>().toEqualTypeOf<string>();
32+
33+
// a trailing defaulted tuple slot stays optional in the input tuple
34+
const tup = z.tuple([z.string(), z.number().default(1)]);
35+
expectTypeOf<z.input<typeof tup>>().toEqualTypeOf<[string, (number | undefined)?]>();
36+
37+
const partialed = objDefault.partial();
38+
expectTypeOf<z.input<typeof partialed>>().toEqualTypeOf<{ a?: string | undefined; b?: number | undefined }>();
39+
});
40+
41+
/* ------------------------------------------------------------------ *
42+
* RUNTIME
43+
* ------------------------------------------------------------------ */
44+
test("ladder: the #6321 regression is fixed", () => {
45+
const arr = z
46+
.string()
47+
.default("")
48+
.transform((v) => (v ? v.split(",") : []));
49+
expect(z.object({ a: arr }).partial().parse({})).toEqual({ a: [] });
50+
expect(z.object({ a: arr }).partial().parse({ a: undefined })).toEqual({ a: [] });
51+
expect(z.object({ a: arr }).partial().parse({ a: "x,y" })).toEqual({ a: ["x", "y"] });
52+
expect(arr.optional().parse(undefined)).toEqual([]);
53+
expect(
54+
z
55+
.string()
56+
.prefault("hi")
57+
.transform((v) => v.length)
58+
.optional()
59+
.parse(undefined)
60+
).toBe(2);
61+
});
62+
63+
test("ladder: key-level admissibility across every rung", () => {
64+
expect(z.object({ a: z.string().default("D") }).parse({})).toEqual({ a: "D" });
65+
expect(z.object({ a: z.string().prefault("P") }).parse({})).toEqual({ a: "P" });
66+
expect(z.object({ a: z.string().optional() }).parse({})).toEqual({});
67+
expect(z.object({ a: z.transform(() => "T") }).parse({})).toEqual({ a: "T" });
68+
expect(z.object({ a: z.string().catch("C") }).parse({})).toEqual({ a: "C" });
69+
expect(z.object({ a: z.string() }).safeParse({}).success).toBe(false);
70+
});
71+
72+
test("ladder: exactOptional keeps its distinct meaning", () => {
73+
expect(z.object({ a: z.string().exactOptional() }).parse({})).toEqual({});
74+
expect(z.object({ a: z.string().exactOptional() }).safeParse({ a: undefined }).success).toBe(false);
75+
});
76+
77+
test("ladder: tuple minimum length respects every rung", () => {
78+
expect(z.tuple([z.string().default("D")]).parse([])).toEqual(["D"]);
79+
expect(z.tuple([z.string().prefault("P")]).parse([])).toEqual(["P"]);
80+
expect(z.tuple([z.string().optional()]).parse([])).toEqual([]);
81+
expect(z.tuple([z.string()]).safeParse([]).success).toBe(false);
82+
expect(z.tuple([z.string(), z.number().default(1)]).parse(["x"])).toEqual(["x", 1]);
83+
});
84+
85+
test("ladder: the #5941 / #5939 clobber invariants still hold", () => {
86+
expect(
87+
z
88+
.preprocess((v) => v ?? "X", z.string())
89+
.optional()
90+
.parse(undefined)
91+
).toBeUndefined();
92+
expect(z.string().catch("X").optional().parse(undefined)).toBeUndefined();
93+
expect(
94+
z
95+
.string()
96+
.catch("X")
97+
.transform((s) => `${s}!`)
98+
.optional()
99+
.parse(undefined)
100+
).toBeUndefined();
101+
expect(
102+
z
103+
.transform(() => "T")
104+
.optional()
105+
.parse(undefined)
106+
).toBeUndefined();
107+
expect(
108+
z
109+
.union([z.preprocess((v) => v ?? "X", z.string()), z.number()])
110+
.optional()
111+
.parse(undefined)
112+
).toBeUndefined();
113+
expect(z.object({ a: z.preprocess((v) => v ?? "X", z.string()) }).parse({})).toEqual({ a: "X" });
114+
});
115+
116+
test("ladder: the top rung survives every wrapper order", () => {
117+
expect(z.string().default("D").optional().parse(undefined)).toBe("D");
118+
expect(z.string().default("D").optional().optional().parse(undefined)).toBe("D");
119+
expect(z.string().default("D").nullable().optional().parse(undefined)).toBe("D");
120+
expect(z.string().default("D").readonly().optional().parse(undefined)).toBe("D");
121+
expect(z.string().default("D").catch("C").optional().parse(undefined)).toBe("D");
122+
expect(z.string().default("D").pipe(z.string()).optional().parse(undefined)).toBe("D");
123+
expect(
124+
z
125+
.union([z.string().default("D"), z.number()])
126+
.optional()
127+
.parse(undefined)
128+
).toBe("D");
129+
expect(
130+
z
131+
.lazy(() => z.string().default("D"))
132+
.optional()
133+
.parse(undefined)
134+
).toBe("D");
135+
});
136+
137+
test("ladder: record and catchall paths that read optin", () => {
138+
expect(z.record(z.string(), z.string().default("D")).parse({ k: undefined })).toEqual({ k: "D" });
139+
expect(z.object({}).catchall(z.string().default("D")).parse({ x: undefined })).toEqual({ x: "D" });
140+
});
141+
142+
test("ladder: async parity", async () => {
143+
const a = z
144+
.string()
145+
.default("")
146+
.transform(async (v) => (v ? v.split(",") : []));
147+
expect((await a.optional().safeParseAsync(undefined)).data).toEqual([]);
148+
expect((await z.object({ a }).partial().safeParseAsync({})).data).toEqual({ a: [] });
149+
expect(
150+
(
151+
await z
152+
.preprocess(async (v) => v ?? "X", z.string())
153+
.optional()
154+
.safeParseAsync(undefined)
155+
).data
156+
).toBeUndefined();
157+
});
158+
159+
test("ladder: the rung values themselves", () => {
160+
expect(z.string()._zod.optin).toBeUndefined();
161+
expect(z.string().optional()._zod.optin).toBe("optional");
162+
expect(z.transform(() => 1)._zod.optin).toBe("optional");
163+
expect(z.string().catch("C")._zod.optin).toBe("optional");
164+
expect(z.string().default("D")._zod.optin).toBe("defaulted");
165+
expect(z.string().prefault("P")._zod.optin).toBe("defaulted");
166+
expect(
167+
z
168+
.string()
169+
.default("D")
170+
.transform((v) => v)._zod.optin
171+
).toBe("defaulted");
172+
expect(z.string().default("D").optional()._zod.optin).toBe("defaulted");
173+
expect(z.union([z.string().default("D"), z.number()])._zod.optin).toBe("defaulted");
174+
expect(z.union([z.string().optional(), z.number()])._zod.optin).toBe("optional");
175+
});

‎packages/zod/src/v4/classic/tests/optional.test.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,35 +27,35 @@ test("optionality", () => {
2727
expect(b._zod.optout).toEqual("optional");
2828

2929
const c = z.string().default("asdf");
30-
expect(c._zod.optin).toEqual("optional");
30+
expect(c._zod.optin).toEqual("defaulted");
3131
expect(c._zod.optout).toEqual(undefined);
3232

3333
const d = z.string().optional().nullable();
3434
expect(d._zod.optin).toEqual("optional");
3535
expect(d._zod.optout).toEqual("optional");
3636

3737
const e = z.string().default("asdf").nullable();
38-
expect(e._zod.optin).toEqual("optional");
38+
expect(e._zod.optin).toEqual("defaulted");
3939
expect(e._zod.optout).toEqual(undefined);
4040

4141
// z.undefined should NOT be optional
4242
const f = z.undefined();
4343
expect(f._zod.optin).toEqual(undefined);
4444
expect(f._zod.optout).toEqual(undefined);
45-
expectTypeOf<typeof f._zod.optin>().toEqualTypeOf<"optional" | undefined>();
45+
expectTypeOf<typeof f._zod.optin>().toEqualTypeOf<"optional" | "defaulted" | undefined>();
4646
expectTypeOf<typeof f._zod.optout>().toEqualTypeOf<"optional" | undefined>();
4747

4848
// z.union should be optional if any of the types are optional
4949
const g = z.union([z.string(), z.undefined()]);
5050
expect(g._zod.optin).toEqual(undefined);
5151
expect(g._zod.optout).toEqual(undefined);
52-
expectTypeOf<typeof g._zod.optin>().toEqualTypeOf<"optional" | undefined>();
52+
expectTypeOf<typeof g._zod.optin>().toEqualTypeOf<"optional" | "defaulted" | undefined>();
5353
expectTypeOf<typeof g._zod.optout>().toEqualTypeOf<"optional" | undefined>();
5454

5555
const h = z.union([z.string(), z.optional(z.string())]);
5656
expect(h._zod.optin).toEqual("optional");
5757
expect(h._zod.optout).toEqual("optional");
58-
expectTypeOf<typeof h._zod.optin>().toEqualTypeOf<"optional">();
58+
expectTypeOf<typeof h._zod.optin>().toEqualTypeOf<"optional" | "defaulted">();
5959
expectTypeOf<typeof h._zod.optout>().toEqualTypeOf<"optional">();
6060
});
6161

@@ -64,7 +64,7 @@ test("pipe optionality", () => {
6464
const a = z.string().optional().pipe(z.string());
6565
expect(a._zod.optin).toEqual("optional");
6666
expect(a._zod.optout).toEqual(undefined);
67-
expectTypeOf<typeof a._zod.optin>().toEqualTypeOf<"optional">();
67+
expectTypeOf<typeof a._zod.optin>().toEqualTypeOf<"optional" | "defaulted">();
6868
expectTypeOf<typeof a._zod.optout>().toEqualTypeOf<"optional" | undefined>();
6969

7070
const b = z
@@ -73,11 +73,11 @@ test("pipe optionality", () => {
7373
.pipe(z.string().optional());
7474
expect(b._zod.optin).toEqual(undefined);
7575
expect(b._zod.optout).toEqual("optional");
76-
expectTypeOf<typeof b._zod.optin>().toEqualTypeOf<"optional" | undefined>();
76+
expectTypeOf<typeof b._zod.optin>().toEqualTypeOf<"optional" | "defaulted" | undefined>();
7777
expectTypeOf<typeof b._zod.optout>().toEqualTypeOf<"optional">();
7878

7979
const c = z.string().default("asdf").pipe(z.string());
80-
expect(c._zod.optin).toEqual("optional");
80+
expect(c._zod.optin).toEqual("defaulted");
8181
expect(c._zod.optout).toEqual(undefined);
8282

8383
const d = z
@@ -202,7 +202,7 @@ test("exactOptional optionality", () => {
202202
const a = z.string().exactOptional();
203203
expect(a._zod.optin).toEqual("optional");
204204
expect(a._zod.optout).toEqual("optional");
205-
expectTypeOf<typeof a._zod.optin>().toEqualTypeOf<"optional">();
205+
expectTypeOf<typeof a._zod.optin>().toEqualTypeOf<"optional" | "defaulted">();
206206
expectTypeOf<typeof a._zod.optout>().toEqualTypeOf<"optional">();
207207
});
208208

‎packages/zod/src/v4/classic/tests/preprocess-types.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ test("ZodPreprocess<B> assignable to ZodPipe<$ZodTransform, B>", () => {
1111

1212
test("ZodPreprocess optin/optout defer to B", () => {
1313
const optionalInside = z.preprocess((v) => v, z.string().optional());
14-
expectTypeOf<(typeof optionalInside)["_zod"]["optin"]>().toEqualTypeOf<"optional">();
14+
expectTypeOf<(typeof optionalInside)["_zod"]["optin"]>().toEqualTypeOf<"optional" | "defaulted">();
1515
expectTypeOf<(typeof optionalInside)["_zod"]["optout"]>().toEqualTypeOf<"optional">();
1616

1717
const required = z.preprocess((v) => v, z.string());
18-
expectTypeOf<(typeof required)["_zod"]["optin"]>().toEqualTypeOf<"optional" | undefined>();
18+
expectTypeOf<(typeof required)["_zod"]["optin"]>().toEqualTypeOf<"optional" | "defaulted" | undefined>();
1919
expectTypeOf<(typeof required)["_zod"]["optout"]>().toEqualTypeOf<"optional" | undefined>();
2020
});
2121

@@ -40,5 +40,5 @@ test("narrowed ZodPreprocess still assignable to the bare type", () => {
4040
const pre = z.preprocess((v: string) => v.length, z.number());
4141
const _bare: z.ZodPreprocess<z.ZodNumber> = pre;
4242
const _bareCore: z.core.$ZodPreprocess = pre;
43-
expectTypeOf<(typeof pre)["_zod"]["optin"]>().toEqualTypeOf<"optional" | undefined>();
43+
expectTypeOf<(typeof pre)["_zod"]["optin"]>().toEqualTypeOf<"optional" | "defaulted" | undefined>();
4444
});

‎packages/zod/src/v4/core/json-schema-processors.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ export const arrayProcessor: Processor<schemas.$ZodArray> = (schema, ctx, _json,
269269
// declared type, so resolve past them to the schema that actually carries the optionality.
270270
// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see
271271
// wiki/optionality.md, "The JSON Schema emitter reads the *static* value".
272-
function inputOptin(schema: schemas.$ZodType): "optional" | undefined {
272+
function inputOptin(schema: schemas.$ZodType): "optional" | "defaulted" | undefined {
273273
const def = schema._zod.def;
274274
if (def.type === "pipe" && (def as schemas.$ZodPipeDef).in._zod.traits.has("$ZodTransform")) {
275275
return inputOptin((def as schemas.$ZodPipeDef).out);
@@ -392,7 +392,7 @@ export const tupleProcessor: Processor<schemas.$ZodTuple> = (schema, ctx, _json,
392392
let minItems = def.items.length;
393393
while (minItems > 0) {
394394
const item = def.items[minItems - 1] as schemas.$ZodType;
395-
const optional = ctx.io === "input" ? inputOptin(item) === "optional" : item._zod.optout === "optional";
395+
const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional";
396396
if (!optional) break;
397397
minItems--;
398398
}

0 commit comments

Comments
 (0)