Skip to content

Commit

Permalink
Bugfix: z.record().parse should not filter out undefined values (#3251)
Browse files Browse the repository at this point in the history
When calling .parse on z.record() we should not filter out undefined values.
Add the optional 'alwaysSet' to the z.record pairs before passing them to mergeObject to
maintain undefined values.

This solves issue #3197
  • Loading branch information
raik-casimiro committed Apr 16, 2024
1 parent 59a2c8f commit 485abbf
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions deno/lib/__tests__/record.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,11 @@ test("is not vulnerable to prototype pollution", async () => {
expect(obj4.data.a).toBeUndefined();
}
});

test("dont parse undefined values", () => {
const result1 = z.record( z.any() ).parse( { foo: undefined } );

expect(result1).toEqual({
foo: undefined,
});
})
2 changes: 2 additions & 0 deletions deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3504,6 +3504,7 @@ export class ZodRecord<
const pairs: {
key: ParseReturnType<any>;
value: ParseReturnType<any>;
alwaysSet: boolean;
}[] = [];

const keyType = this._def.keyType;
Expand All @@ -3515,6 +3516,7 @@ export class ZodRecord<
value: valueType._parse(
new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
),
alwaysSet: key in ctx.data,
});
}

Expand Down
8 changes: 8 additions & 0 deletions src/__tests__/record.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,11 @@ test("is not vulnerable to prototype pollution", async () => {
expect(obj4.data.a).toBeUndefined();
}
});

test("dont parse undefined values", () => {
const result1 = z.record( z.any() ).parse( { foo: undefined } );

expect(result1).toEqual({
foo: undefined,
});
})
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3504,6 +3504,7 @@ export class ZodRecord<
const pairs: {
key: ParseReturnType<any>;
value: ParseReturnType<any>;
alwaysSet: boolean;
}[] = [];

const keyType = this._def.keyType;
Expand All @@ -3515,6 +3516,7 @@ export class ZodRecord<
value: valueType._parse(
new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
),
alwaysSet: key in ctx.data,
});
}

Expand Down

0 comments on commit 485abbf

Please sign in to comment.