0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.