How to implement a pluck function in TypeScript?

前端 未结 2 1210
遥遥无期
遥遥无期 2021-01-25 14:41

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

相关标签:
2条回答
  • 2021-01-25 15:28

    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']);
    
    0 讨论(0)
  • 2021-01-25 15:28

    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>;
    }
    
    0 讨论(0)
提交回复
热议问题