Skip to content

Commit 4e1720c

Browse files
authored
fix(v4): align record keys and intersection strictness with TypeScript (#6412)
* fix(record): classify an out-of-set key by whether the key schema is enumerable An enumerable key schema (z.enum, z.literal([...])) declares which keys the record owns, so a key outside that set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the first is reconcilable against the other side of an intersection, which handleIntersectionResults already does for unrecognized_keys. The branch that emitted the issue keyed off def.partial rather than the key schema, so partialRecord(z.enum([...])) reported invalid_key and its keys were never reconciled -- the object side of an intersection could not claim its own keys. Fixes #2200, #2573. * fix(record): a record's key schema governs its own keys, not every key A record's key schema declares which keys that record is responsible for. It is not a predicate every key in the result must satisfy. TypeScript agrees: in `{name: string} & Record<\`S_\${string}\`, string>` the index signature constrains only the keys matching it, so `name` is accepted, while a matching key with the wrong value type is still an error. Zod's inferred types already match TypeScript here, but the runtime rejected the object's own keys with invalid_key, so z.infer accepted values the parser threw on. Two changes: - partialRecord with an enumerable key schema now reports an out-of-set key as unrecognized_keys, like z.record(z.enum([...])) already did. The branch keyed off def.partial rather than off the key schema. - handleIntersectionResults reconciles a record's invalid_key the same way it already reconciles unrecognized_keys, so a key one side does not govern is reported only when neither side governs it. Standalone records are unchanged: a key outside the key schema is still an error, matching TypeScript's excess-property check on a fresh literal. Fixes #2200, #2573. * fix(v4): let an unrecognized key continue, so operands run their own logic unrecognized_keys describes the shape of the input, not the validity of the parsed value, so it no longer aborts the schema it came from. A strict operand inside an intersection now runs its own checks, refinements and transforms, a nested default still applies, and an extra key no longer suppresses the other errors on the same object. The parse still fails. A pipe keeps its rule that any issue stops it, so a failing refinement never feeds its transform -- the one exception is unrecognized_keys, where the value handed downstream is identical whether or not the extra key was present.
1 parent 4cc4053 commit 4e1720c

3 files changed

Lines changed: 182 additions & 38 deletions

File tree

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

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,3 +214,121 @@ test("invalid deep merge of object and array combination", async () => {
214214
`[Error: Unmergable intersection. Error path: ["students",0,"name"]]`
215215
);
216216
});
217+
218+
// A record's key schema says which keys that record GOVERNS; it is not a predicate
219+
// every key in the result must satisfy. TypeScript works the same way: in
220+
// `{name: string} & Record<`S_${string}`, string>` the index signature constrains
221+
// only the keys matching it, so `name` is fine. So a key one side does not govern
222+
// is reconciled against the other side, exactly as unrecognized_keys already is.
223+
test("a record's key schema governs only its own keys inside an intersection", () => {
224+
const Obj = z.object({ name: z.string() });
225+
const value = { name: "a", S_a: "s" };
226+
227+
// Every key-schema flavor behaves the same: `name` belongs to the object side.
228+
expect(z.intersection(Obj, z.record(z.string().regex(/^S_/), z.string())).parse(value)).toEqual(value);
229+
expect(z.intersection(Obj, z.record(z.templateLiteral(["S_", z.string()]), z.string())).parse(value)).toEqual(value);
230+
expect(z.intersection(Obj, z.partialRecord(z.enum(["p1", "p2"]), z.string())).parse({ name: "a", p1: "x" })).toEqual({
231+
name: "a",
232+
p1: "x",
233+
});
234+
expect(z.intersection(Obj, z.record(z.enum(["p1"]), z.string())).parse({ name: "a", p1: "x" })).toEqual({
235+
name: "a",
236+
p1: "x",
237+
});
238+
239+
// A key the record DOES govern still has its value validated across the intersection.
240+
const governed = z.intersection(z.object({ S_x: z.number() }), z.record(z.string().regex(/^S_/), z.string()));
241+
expect(governed.safeParse({ S_x: 1 }).success).toBe(false);
242+
243+
// A key NEITHER side governs is still rejected.
244+
const strict = z.intersection(z.strictObject({ name: z.string() }), z.record(z.string().regex(/^S_/), z.string()));
245+
expect(strict.parse(value)).toEqual(value);
246+
expect(strict.safeParse({ ...value, evil: "q" }).success).toBe(false);
247+
248+
// Standalone, a record still rejects a key it does not govern.
249+
expect(z.record(z.string().regex(/^S_/), z.string()).safeParse({ S_a: "s", bad: "x" }).success).toBe(false);
250+
});
251+
252+
test("partialRecord reports an out-of-set key as unrecognized, not invalid", () => {
253+
const enumKeys = z.partialRecord(z.enum(["a", "b"]), z.string()).safeParse({ a: "x", zzz: "q" });
254+
expect(enumKeys.success).toBe(false);
255+
expect(enumKeys.error!.issues[0].code).toBe("unrecognized_keys");
256+
257+
// A regex key schema still reports the failure as an invalid key.
258+
const regexKeys = z.record(z.string().regex(/^S_/), z.string()).safeParse({ S_a: "x", zzz: "q" });
259+
expect(regexKeys.success).toBe(false);
260+
expect(regexKeys.error!.issues[0].code).toBe("invalid_key");
261+
});
262+
263+
test("intersection operands run their own checks, refinements and transforms", () => {
264+
let checks = 0;
265+
const failing = z.intersection(
266+
z.strictObject({ x: z.string() }).check(() => {
267+
checks++;
268+
}),
269+
z.strictObject({ a: z.string() }).superRefine((_data, ctx) => {
270+
checks++;
271+
ctx.addIssue({ code: "custom", message: "boom" });
272+
})
273+
);
274+
expect(failing.safeParse({ x: "test", a: "hello" })).toMatchObject({
275+
success: false,
276+
error: { issues: [{ code: "custom", message: "boom" }] },
277+
});
278+
expect(checks).toBe(2);
279+
280+
const transformed = z.intersection(
281+
z.strictObject({ x: z.string() }).transform((v) => ({ ...v, x: v.x.toUpperCase() })),
282+
z.strictObject({ a: z.string() }).transform((v) => ({ ...v, seen: true }))
283+
);
284+
expect(transformed.parse({ x: "test", a: "hello" })).toEqual({ x: "TEST", a: "hello", seen: true });
285+
});
286+
287+
test("intersection operands apply defaults, including through a nested intersection", () => {
288+
const inner = z.intersection(
289+
z.strictObject({ x: z.string().default("X default"), y: z.number() }),
290+
z.strictObject({ z: z.boolean() })
291+
);
292+
const schema = z.intersection(inner, z.strictObject({ a: z.string() }));
293+
expectTypeOf<z.output<typeof schema>>().toEqualTypeOf<{ x: string; y: number } & { z: boolean } & { a: string }>();
294+
295+
expect(schema.parse({ y: 34, z: true, a: "hello" })).toEqual({ x: "X default", y: 34, z: true, a: "hello" });
296+
});
297+
298+
test("a record operand runs its own refinements inside an intersection", () => {
299+
let calls = 0;
300+
const schema = z
301+
.record(z.enum(["p1", "p2"]), z.string())
302+
.superRefine((_data, ctx) => {
303+
calls++;
304+
ctx.addIssue({ code: "custom", message: "record refined" });
305+
})
306+
.and(z.strictObject({ name: z.string() }));
307+
308+
expect(schema.safeParse({ p1: "a", p2: "b", name: "n" })).toMatchObject({
309+
success: false,
310+
error: { issues: [{ code: "custom", message: "record refined" }] },
311+
});
312+
expect(calls).toBe(1);
313+
});
314+
315+
test("a strict object nested under an operand keeps its strictness", () => {
316+
const schema = z.intersection(
317+
z.object({ inner: z.strictObject({ a: z.string() }) }),
318+
z.object({ other: z.string() })
319+
);
320+
321+
expect(schema.parse({ inner: { a: "x" }, other: "y" })).toEqual({ inner: { a: "x" }, other: "y" });
322+
expect(schema.safeParse({ inner: { a: "x", extra: 1 }, other: "y" })).toMatchObject({
323+
success: false,
324+
error: { issues: [{ code: "unrecognized_keys", keys: ["extra"], path: ["inner"] }] },
325+
});
326+
});
327+
328+
test("a strict object composes with a refined object", () => {
329+
const A = z.object({ key1: z.boolean() }).strict();
330+
const B = z.object({ key2: z.boolean() }).refine(({ key2 }) => key2, "key2 must be true");
331+
332+
expect(A.and(B).parse({ key1: true, key2: true })).toEqual({ key1: true, key2: true });
333+
expect(A.and(B).safeParse({ key1: true, key2: false }).success).toBe(false);
334+
});

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

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -561,24 +561,12 @@ test("partialRecord with z.literal([key, ...])", () => {
561561
{
562562
"error": [ZodError: [
563563
{
564-
"code": "invalid_key",
565-
"origin": "record",
566-
"issues": [
567-
{
568-
"code": "invalid_value",
569-
"values": [
570-
"id",
571-
"name",
572-
"email"
573-
],
574-
"path": [],
575-
"message": "Invalid option: expected one of \\"id\\"|\\"name\\"|\\"email\\""
576-
}
577-
],
578-
"path": [
564+
"code": "unrecognized_keys",
565+
"keys": [
579566
"foo"
580567
],
581-
"message": "Invalid key in record"
568+
"path": [],
569+
"message": "Unrecognized key: \\"foo\\""
582570
}
583571
]],
584572
"success": false,

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

Lines changed: 60 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1957,6 +1957,10 @@ function handleCatchall(
19571957
keys: unrecognized,
19581958
input,
19591959
inst,
1960+
// Describes the shape of the input, not the validity of the parsed value, so it never
1961+
// aborts. The parse still fails; the schema's own checks just get to run first, and an
1962+
// enclosing intersection can reconcile the key against a sibling operand.
1963+
continue: true,
19601964
});
19611965
}
19621966

@@ -2624,44 +2628,55 @@ function mergeValues(
26242628
}
26252629

26262630
function handleIntersectionResults(result: ParsePayload, left: ParsePayload, right: ParsePayload): ParsePayload {
2627-
// Track which side(s) report each key as unrecognized
2631+
// Track which side(s) reject each key. A key rejection is reported only when
2632+
// BOTH sides reject it, so a key owned by one branch survives the other's
2633+
// key schema. strictObject reports these as unrecognized_keys; a record with
2634+
// an open key schema reports one invalid_key per key.
26282635
const unrecKeys = new Map<string, { l?: true; r?: true }>();
26292636
let unrecIssue: errors.$ZodRawIssue | undefined;
2637+
const keyIssues = new Map<string, errors.$ZodRawIssue>();
26302638

2631-
for (const iss of left.issues) {
2632-
if (iss.code === "unrecognized_keys") {
2639+
const collect = (iss: errors.$ZodRawIssue, side: "l" | "r"): boolean => {
2640+
let keys: string[];
2641+
if (iss.code === "unrecognized_keys" && !iss.path?.length) {
26332642
unrecIssue ??= iss;
2634-
for (const k of iss.keys) {
2635-
if (!unrecKeys.has(k)) unrecKeys.set(k, {});
2636-
unrecKeys.get(k)!.l = true;
2637-
}
2643+
keys = iss.keys as string[];
2644+
} else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
2645+
const k = String(iss.path[0]);
2646+
if (!keyIssues.has(k)) keyIssues.set(k, iss);
2647+
keys = [k];
26382648
} else {
2639-
result.issues.push(iss);
2649+
return false;
26402650
}
2651+
for (const k of keys) {
2652+
if (!unrecKeys.has(k)) unrecKeys.set(k, {});
2653+
unrecKeys.get(k)![side] = true;
2654+
}
2655+
return true;
2656+
};
2657+
2658+
for (const iss of left.issues) {
2659+
if (!collect(iss, "l")) result.issues.push(iss);
26412660
}
26422661

26432662
for (const iss of right.issues) {
2644-
if (iss.code === "unrecognized_keys") {
2645-
for (const k of iss.keys) {
2646-
if (!unrecKeys.has(k)) unrecKeys.set(k, {});
2647-
unrecKeys.get(k)!.r = true;
2648-
}
2649-
} else {
2650-
result.issues.push(iss);
2651-
}
2663+
if (!collect(iss, "r")) result.issues.push(iss);
26522664
}
26532665

2654-
// Report only keys unrecognized by BOTH sides
2666+
// Report only keys rejected by BOTH sides
26552667
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
2656-
if (bothKeys.length && unrecIssue) {
2657-
result.issues.push({ ...unrecIssue, keys: bothKeys });
2668+
if (bothKeys.length) {
2669+
const aggregated = unrecIssue ? bothKeys.filter((k) => (unrecIssue!.keys as string[]).includes(k)) : [];
2670+
if (aggregated.length) result.issues.push({ ...unrecIssue!, keys: aggregated });
2671+
for (const k of bothKeys) {
2672+
if (!aggregated.includes(k) && keyIssues.has(k)) result.issues.push(keyIssues.get(k)!);
2673+
}
26582674
}
26592675

2660-
if (util.aborted(result)) return result;
2661-
26622676
const merged = mergeValues(left.value, right.value);
26632677

26642678
if (!merged.valid) {
2679+
if (util.aborted(result)) return result;
26652680
throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
26662681
}
26672682

@@ -3032,10 +3047,16 @@ export const $ZodRecord: core.$constructor<$ZodRecord> = /*@__PURE__*/ core.$con
30323047
input,
30333048
inst,
30343049
keys: unrecognized,
3050+
continue: true,
30353051
});
30363052
}
30373053
} else {
30383054
payload.value = {};
3055+
// An enumerable key schema declares which keys the record owns, so a key outside
3056+
// the set is unrecognized. A non-enumerable one (regex, refine) is a constraint
3057+
// every key must satisfy, so a failing key is invalid. Only the former is
3058+
// reconcilable against the other side of an intersection.
3059+
let unrecognized!: string[];
30393060
// Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()
30403061
for (const key of Reflect.ownKeys(input)) {
30413062
if (key === "__proto__") continue;
@@ -3062,6 +3083,9 @@ export const $ZodRecord: core.$constructor<$ZodRecord> = /*@__PURE__*/ core.$con
30623083
if (def.mode === "loose") {
30633084
// Pass through unchanged
30643085
payload.value[key] = input[key];
3086+
} else if (values) {
3087+
unrecognized = unrecognized ?? [];
3088+
unrecognized.push(key as string);
30653089
} else {
30663090
// Default "strict" behavior: error on invalid key
30673091
payload.issues.push({
@@ -3099,6 +3123,17 @@ export const $ZodRecord: core.$constructor<$ZodRecord> = /*@__PURE__*/ core.$con
30993123
payload.value[outKey] = result.value;
31003124
}
31013125
}
3126+
3127+
if (unrecognized && unrecognized.length > 0) {
3128+
payload.issues.push({
3129+
code: "unrecognized_keys",
3130+
3131+
input,
3132+
inst,
3133+
keys: unrecognized,
3134+
continue: true,
3135+
});
3136+
}
31023137
}
31033138

31043139
if (proms.length) {
@@ -4125,7 +4160,10 @@ export const $ZodPipe: core.$constructor<$ZodPipe> = /*@__PURE__*/ core.$constru
41254160
});
41264161

41274162
function handlePipeResult(left: ParsePayload, next: $ZodType, ctx: ParseContextInternal) {
4128-
if (left.issues.length) {
4163+
// Any issue stops the pipe, so a failing refinement never feeds its transform. An
4164+
// unrecognized key is the exception: it describes the input's extra properties, not the
4165+
// value being piped, and an enclosing intersection may yet reconcile it.
4166+
if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
41294167
// prevent further checks
41304168
left.aborted = true;
41314169
return left;

0 commit comments

Comments
 (0)