【发布时间】:2020-09-10 20:31:40
【问题描述】:
我正在尝试使用 Array.prototype.reduce 规范化一些数据。
我想知道为什么我可以打破reduce 函数中的“类型检查”。
这是我的界面。
interface Dict<T> {
[key:string]: T;
}
interface InnerData {
id: string;
value: number;
}
interface RawData {
innerData: InnerData[];
}
interface NormalizedData {
innerData: Dict<InnerData>
}
以下是我打算如何使用这些接口的示例。
const rawData: RawData = {
innerData: [
{
id: "ID_ONE",
value: 1
},
{
id: "ID_TWO",
value: 2
}
]
};
const normalizedData: NormalizedData = {
innerData: this.noramlizeInner(rawData.innerData),
};
private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
return innerData.reduce((acc:Dict<InnerData>, curr: InnerData) => {
return {
...acc,
[curr.id]: {
...curr
}
}
}, {});
}
但是,如果我更改normalizeInner,我仍然可以编译,并且返回值不正确。
private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
return innerData.reduce((acc, curr: InnerData) => { // changed acc:Dict<InnerData> to acc in the signature.
return {
...acc,
[curr.id]: [curr]
}
}, {});
}
重申问题,我想知道我在reduce函数中做错了什么,为什么它还在编译。
这是用于演示的 CodeSandBox 应用程序 (LINK)。
【问题讨论】:
-
看起来在
reduce()和implicit index signatures 中推断的空对象类型{}之间的交互很差。可能这里的解决方法是指定像innerData.reduce<Dict<InnerData>>(...)这样的泛型,而不是让它被推断为{} -
(如this)
标签: arrays typescript generics normalization reduce