gpt4 book ai didi

javascript - 如何在 TypeScript 中将数组转换为对象?

转载 作者:行者123 更新时间:2023-12-05 05:55:48 29 4
gpt4 key购买 nike

我正在尝试输入下面的实用函数,它接受一个数组并返回一个对象,如下所示

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'));

如你所知keysecondKey是动态的,取决于参数 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变量很好,但我在 Record 声明行遇到错误,错误如下

Type 'T[U]' does not satisfy the constraint 'string | number | symbol'.Type 'T[keyof T]' is not assignable to type 'string | number | symbol'.Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'string | number | symbol'.Type 'T[string]' is not assignable to type 'string | number | symbol'.Type 'T[string]' is not assignable to type 'symbol'.Type 'T[keyof T]' is not assignable to type 'symbol'.Type 'T[U]' is not assignable to type 'symbol'.Type 'T[keyof T]' is not assignable to type 'symbol'.Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'symbol'.Type 'T[string]' is not assignable to type 'symbol'.ts(2344)

最佳答案

最后一次尝试的问题是 Record似乎只期待string | number | symbol ,并且由于 TypeScript 不确定是什么 T[U]会的,因此它引发了错误。我发现我们可以告诉 TS 更多关于 T 的信息如下

const convertListToMap = <
T extends { [key: string|number]: string | number },
U extends keyof T,
V extends keyof T
>(
list: T[],
key: U,
secondKey: V
) => {
const map = {} as Record<T[U], T[V]>;
for (const ele of list) {
map[ele[key]] = ele[secondKey];
}
return map;
};

从上面,我们告诉 typescript T将成为 key 的对象的 string , 并且该值将是 string | number 类型,因此,TypeScript 对定义 Record<T[U], T[V]> 很满意

这个解决方案效果很好,TS 可以正确推断

const personObj = convertListToMap([{name: 'isaac', age: 17}, {name: 'john', age: 20}], 'name', 'age')
// const personObj: Record<string, number>

const languageObj = convertListToMap([{race: 'chinese', language: 'mandarin'}, {race: 'malay', language: 'melayu'}], 'race', 'language')
// const languageObj: Record<string,string>

关于javascript - 如何在 TypeScript 中将数组转换为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69357555/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com