How to implement a pluck function in TypeScript?

前端 未结 2 1211
遥遥无期
遥遥无期 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

    Here's an alternative option:

    function pluck(objs: T, keys: K[]): Pick {
      return keys.reduce((result, key) => 
        Object.assign(result, {[key as string]: objs[key]}), {}) as Pick;
    }
    

提交回复
热议问题