如何在TypeScript中根据对象传入的key返回这些key的推断?-灵析社区

萌蒙萌

typescript,函数如何根据传入的key,返回对象对应的这些key?比如: const obj = { name: 'Marcelo', age: 27, role: ['admin'] }; type ObjType = { [key in keyof typeof obj]: typeof obj[key] } const getAttr = >(...attribute: KS): T[KS] => { const result = {}; for (const attr of attribute) { result[attr] = obj[attr]; } return result; }; const attr = getAttr('age', 'name'); 现在这个写法肯定不对,变量attr的推断是unknown,如何写函数getAttr的返回定义,才能让变量attr的推断为{age:number, name:string },就是函数传入了哪些key,就只返回这些key的推断

阅读量:21

点赞量:0

问AI
想到了,使用Pick就可以了,如下: const obj = { name: 'Marcelo', age: 27, role: ['admin'] }; type ObjType = { [key in keyof typeof obj]: typeof obj[key] } const getAttr = (...attribute: Array): Pick[number]> => { const result = {}; for (const attr of attribute) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore result[attr] = obj[attr]; } return result as Pick[number]>; }; const attr = getAttr('age', 'name'); 有更好的答案,欢迎补充!