我试图输入下面的实用函数,该函数接受一个数组并返回以下对象。
在这最新的尝试中,对
类型'T[U]'不能满足约束条件'string | number | symbol'。 类型“T[keyof T]”不能赋值给类型“string | number | symbol”。 类型“T[string] | T[number] | T[symbol]”不能赋值给类型“string | number | symbol”。 类型“T[string]”不能赋值给类型“string | number | symbol”。 类型“T[string]”不能赋值给类型“symbol”。 类型“T[keyof T]”不能赋值给类型“symbol”。 类型“T[U]”不能赋值给类型“symbol”。 类型“T[keyof T]”不能赋值给类型“symbol”。 类型“T[string] | T[number] | T[symbol]”不能赋值给类型“symbol”。 类型“T[string]”不能赋值给类型“symbol”。ts(2344)
const convertListToMap = (list, key, secondKey) => {
const map = {};
for (const ele of list) {
map[ele[key]] = ele[secondKey]
}
return map;
}
console.log(convertListToMap([{name: 'isaac', age: 17}, {name: 'john', age: 20}], 'name', 'age'));
console.log(convertListToMap([{race: 'chinese', language: 'mandarin'}, {race: 'malay', language: 'melayu'}], 'race', 'language'));
如您所见,key
和 secondKey
是有点动态的,取决于参数 list
,因此我想使用 generics
。以下是我的尝试:
const convertListToMap = <
T extends object,
U extends keyof T,
V extends keyof T
>(
list: T[],
key: U,
secondKey: V
) => {
const map = {} as Record<U, V>;
for (const ele of list) {
map[ele[key]] = ele[secondKey];
}
return map;
};
然而,上述代码报错提示 Type 'T[U]' cannot be used to index type 'Record<U, V>'
,不知道哪里出错了?
更新
我最新的尝试是按照以下方式更新map
方法的签名:
const map = {} as Record<T[U], T[V]>;
for (const ele of list) {
map[ele[key]] = ele[secondKey];
}
return map;
在这最新的尝试中,对
map
变量进行值分配很好,但我在下面记录声明行处遇到错误:类型'T[U]'不能满足约束条件'string | number | symbol'。 类型“T[keyof T]”不能赋值给类型“string | number | symbol”。 类型“T[string] | T[number] | T[symbol]”不能赋值给类型“string | number | symbol”。 类型“T[string]”不能赋值给类型“string | number | symbol”。 类型“T[string]”不能赋值给类型“symbol”。 类型“T[keyof T]”不能赋值给类型“symbol”。 类型“T[U]”不能赋值给类型“symbol”。 类型“T[keyof T]”不能赋值给类型“symbol”。 类型“T[string] | T[number] | T[symbol]”不能赋值给类型“symbol”。 类型“T[string]”不能赋值给类型“symbol”。ts(2344)
map
不是类型Record<U,V>
,因为你放入的值来自T
,而不是键。 - Philconst map = {} as Record<T[U], T[V]>;
但它也不起作用哈哈。 - Isaac