fix(collections): ensure pick doesn't generate missing properties as undefined (#5926)

This commit is contained in:
Sʜɪᴍᴜʀᴀ Yū 2024-09-12 15:25:38 +09:00 committed by GitHub
parent 7d3dd2db03
commit 1a3a515ae5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 1 deletions

View File

@ -28,5 +28,7 @@ export function pick<T extends object, K extends keyof T>(
obj: Readonly<T>,
keys: readonly K[],
): Pick<T, K> {
return Object.fromEntries(keys.map((k) => [k, obj[k]])) as Pick<T, K>;
const result = {} as Pick<T, K>;
for (const key of keys) if (key in obj) result[key] = obj[key];
return result;
}

View File

@ -14,6 +14,19 @@ Deno.test({
},
});
Deno.test({
name:
"pick() returns a new object without properties missing in the original object",
fn() {
// deno-lint-ignore no-explicit-any
const obj = { a: 5, b: 6, c: 7, d: 8 } as any;
const picked: { a: 5; x?: 5; y?: 5 } = pick(obj, ["a", "x", "y"]);
assertEquals(picked, { a: 5 });
assertNotStrictEquals(picked, obj);
},
});
Deno.test({
name:
"pick() returns a new object from the provided object with the provided keys",