There are two basic types of data available:
type DataA = {
percent: string;
exchange: string;
};
type DataB = {
price: number;
exchange: string;
};
I'm puzzled as to why TypeScript gives errors when I try to use both types together:
const sumData = (
assets: DataA[] | DataB[],
summedBy: string,
total: string
) => {
const uniqueMap = assets.reduce((acc, el: DataA | DataB) => {
if (acc.has(el[summedBy])) {
acc.set(el[summedBy], {
...acc.get(el[summedBy]),
[total]: acc.get(el[summedBy])[total] =
+acc.get(el[summedBy])[total] + parseFloat(el[total])
});
} else {
acc.set(el[summedBy], el);
}
return acc;
}, new Map());
return [...uniqueMap.values()];
};
However, there are no errors when I combine the two types into a single shape:
type CombinedShape = DataA | DataB;
Why does this discrepancy occur? https://codesandbox.io/s/16vzvqqv3 (Errors.ts and NoErrors.ts)