I cannot figure out how to type a return type of a reduce function. Please have a look at the ts playground link. I'm providing a callback function to the reduce fn that takes two params as number[] and returns a number, but typescript throws an error saying that return type of this operation supposed to be number[]. As a workaround I've tried to explicitly provide a return "as number" but ts throws again saying that it might be a mistake. So the question is how can I force it and change reduce signature to return the type I want?
export function sumOfIntervals(intervals: [number, number][]): number {
const mergedIntervals: [number, number][] = [];
intervals
.sort(([a], [b]) => a - b)
.reduce((prev, curr) => {
const [prevMin, prevMax] = prev;
const [currMin] = curr;
if (prevMax > currMin && currMin > prevMin) {
mergedIntervals.push([Math.min(...prev, ...curr), Math.max(...prev, ...curr)])
} else {
mergedIntervals.push(curr)
}
return curr;
})
return mergedIntervals.reduce(([a, b], [c, d]) => ((b - a) + (d - c))); /* err */
}
Error:
Type '[number, number]' is not assignable to type 'number'.(2322)
Code snippet here
Extending from Eduard's comment, in your use case of Array.prototype.reduce, you are returning a number, but you are attempting to destructure a number into [number, number] in the first argument. If you simply want to sum all the differences, you don't need to unpack it:
return mergedIntervals.reduce((acc, [a, b]) => acc + (b-a), 0);
That is because the current value (second positional argument) will always be your [number, number] tuple, and you simply want to add their difference into an accumulator, which has a type of number.
See fixed example on TypeScript playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With