Attempting to standardize data using Array.prototype.reduce.
Puzzled by how I can bypass "type-checking" in the reduce
function.
My interfaces:
interface Dict<T> {
[key:string]: T;
}
interface InnerData {
id: string;
value: number;
}
interface RawData {
innerData: InnerData[];
}
interface NormalizedData {
innerData: Dict<InnerData>
}
Examples of how I intended to use these interfaces:
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
}
}
}, {});
}
However, when I modify the normalizeInner
, it still compiles and the returned value is unexpectedly incorrect.
private noramlizeInner(innerData: InnerData[]): Dict<InnerData> {
return innerData.reduce((acc, curr: InnerData) => {
return {
...acc,
[curr.id]: [curr]
}
}, {});
}
To reiterate my question, what mistake did I make in the reduce
function that allows it to compile?
CodeSandBox app for demonstration: (LINK)