Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/06-challenges/29.5-pick.solution2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { expect, it } from "vitest";
import { Equal, Expect } from "../helpers/type-utils";

const pick = <TObj, TPicked extends keyof TObj>(
obj: TObj,
picked: Array<TPicked>
) => {
return picked.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {} as {[PickedKey in TPicked]: TObj[PickedKey]});
};

it("Should pick the keys from the object", () => {
const result = pick(
{
a: 1,
b: 2,
c: 3,
d: true
},
["a", "b", "d"]
);

expect(result).toEqual({ a: 1, b: 2 });

type test = Expect<Equal<typeof result, { a: number; b: number, d: boolean }>>;
});

it("Should not allow you to pass keys which do not exist in the object", () => {
pick(
{
a: 1,
b: 2,
c: 3,
},
[
"a",
"b",
// @ts-expect-error
"d",
]
);
});