I often need to pluck properties out of an object
const obj = {a:1, b: 2, c: 3};
const plucked = pluck(obj, \'a\', \'b\'); // {a: 1, b:2}
Howev
I ended up using any
on the object that I manipulate and TypeScript is happy allowing that as a return value. See it in action
function pluck<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const ret: any = {};
for (let key of keys) {
ret[key] = obj[key];
}
return ret;
}
const less = pluck({ a: 1, b: '2', c: true }, ['a', 'c']);
Here's an alternative option:
function pluck<T, K extends keyof T>(objs: T, keys: K[]): Pick<T, K> {
return keys.reduce((result, key) =>
Object.assign(result, {[key as string]: objs[key]}), {}) as Pick<T, K>;
}