Search code examples
typescripttsc

issue when applying function reduce to empty array


The typescript compiler does not mark any errors with the following code.

const numbers: number[] = [];
const sum: number = numbers.reduce((a, num) => (a + num));

However, when executing the transposed code, nodejs returns the following exception

TypeError: Reduce of empty array with no initial value

I think this can cause many runtime errors and perhaps typescript should suggest that I check if the array is not empty before using the reduce function.

const numbers: number[] = [];
const sum: number = numbers.length > 0 ? numbers.reduce((a, num) => (a + num)) : 0;

Should I report it as an issue?


Solution

  • I doubt that anybody will change this. The Typescript compiler is only interested in whether you instantisted the array correctly.

    And this you did.

    Java, for example, does the same. As long as a variable is instantiated properly, the programmer is responsible itself for whether it has a content or not.