How to implement a pluck function in TypeScript?

前端 未结 2 1212
遥遥无期
遥遥无期 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条回答
  •  -上瘾入骨i
    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(obj: T, keys: K[]): Pick {
        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']);
    

提交回复
热议问题