【发布时间】:2022-09-27 19:30:01
【问题描述】:
我正在尝试为将数组转换为对象的函数编写泛型类型,如下所示:
type ObjType = { id: number; name: string; status: string };
const zzx: ObjType[] = [
{
id: 1,
name: \"A\",
status: \"a\"
},
{
id: 2,
name: \"B\",
status: \"b\"
},
{
id: 3,
name: \"C\",
status: \"c\"
}
];
function arrayToObject<T>(
arr: T[],
key: string | number
): Record<string | number, T> {
const result: Record<string, T> = {};
for (const item of arr) {
const value = item[key as keyof typeof T];
result[value] = item;
}
return result;
}
const xx = arrayToObject<ObjType>(zzx, \"id\");
我在某处读到泛型类型可以作为 <> 括号中的参数传递。
但是,我在从函数调用传递的函数中看不到类型(ObjType)。
并且还低于item[key as keyof typeof T]; 行中的错误
Element implicitly has an \'any\' type because expression of type \'string | number | symbol\' can\'t be used to index type \'unknown\'.
No index signature with a parameter of type \'string\' was found on type \'unknown\'.
有人可以告诉我我做错了什么吗?
标签: reactjs typescript