我在TypeScript中使用reduce()有麻烦。我想将具有相同键/值对的对象减少到一个数组中。
我正在尝试这样做:
const asdf = sections.reduce<{ [index: number]: any }>((res, section) => {
return [
...res, //error here
{
[section.buildingId]: [
...(res[section.buildingId] || []),
section,
],
},
]
},[]) //I think the problem lies here?!
}
sections是一个对象数组,这些对象的键值都是buildingId: number。我怀疑[]的初始值是问题的根源,但我不太确定。
第三行给出了这个错误:
Type '{[index: number]: any;}必须有一个符号。返回迭代器的迭代器方法。ts(2488)
这对我来说很奇怪,因为number是可迭代的?!或不呢?
将类型更改为Array:
const asdf = sections.reduce<Array<any>>((res, section) => {
return [
...res,
{
[section.buildingId]: [
...(res[section.buildingId] || []),
section,
],
},
]
},[])