One task I face frequently is extracting specific properties from an object
const obj = {a:1, b: 2, c: 3};
const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2}
Unfortunately, achieving this task with type safety in TypeScript can be challenging. Implementing a function with the signature mentioned in TypeScript's documentation isn't straightforward.
declare function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K>;
I attempted to create my own version without success. Here is the code snippet I tried:
function pluck<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
// Type '{}' is not assignable to type 'Pick<T, K>'.
const ret: Pick<T, K> = {};
for (let key of keys) {
ret[key] = obj[key];
}
return ret;
}
Does this mean I am required to use ambient declarations and define the function in JavaScript instead?