我已经找到了解决方案,但我就是不明白为什么不添加一个返回类型来解决这个问题:
我有一个根据ID而不是数组来键入TypeORM实体的函数.
import { instanceToPlain } from 'class-transformer';
export default function keyBy(
listOfObjects: object[],
mappingKey: string,
): object // <--- i had to remove this
{
const data = listOfObjects.reduce((acc: any, currentVal: any) => {
const tempObj = instanceToPlain(currentVal);
if (tempObj[mappingKey] === undefined) {
throw new Error(`Mapping key:${mappingKey} not found in the Array`);
}
acc[tempObj[mappingKey]] = currentVal;
return acc;
}, {});
return data;
}
我必须删除对象返回类型,否则下面的代码行会给出错误.
const usersById = keyBy(users, 'id');
const user = usersById[message.senderId];
为了理解,我try 了几种方法,包括:
const user = usersById[Object.keys(usersById)[0] as keyof typeof usersById];
个
但后来我得到了:
Property 'firstName' does not exist on type 'never'.
个
无论如何,删除key By的返回类型可以解决这些错误,但我真的很想了解这里发生了什么.