Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly type return type of a reduce function

Tags:

typescript

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

like image 410
Lukasz Kisicki Avatar asked Nov 17 '25 14:11

Lukasz Kisicki


1 Answers

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.

like image 118
Terry Avatar answered Nov 19 '25 10:11

Terry