If I were to utilize Typescript to create a function called mean
that calculates the mean of an array of number
s, how should I handle the scenario where the array is empty?
Enforcing that an array must be non-empty can be inconvenient, so what would be the best way to communicate to users of the mean
function that it is not defined for empty arrays?
Here are some potential options:
- Return
NaN
.
While using NaN
may seem like an appropriate choice, tracking down the source of NaN
values can be problematic as it provides limited information about the error. It's only revealed at runtime.
- Return
undefined
(updating the type to
).(nums: number[]) => number | undefined
Although not ideal, returning undefined
offers more clarity than option 1. since the type indicates that something could potentially go wrong. However, it lacks details on the reason for failure.
- Throw an error.
This approach delivers a descriptive message concerning the issue at hand. Yet, it does establish a direct dependency between the caller and the implementation.
- Return
undefined
while logging an error message.
By combining the type information from option 2. with the explanatory aspect of option 3., this method provides a balanced approach. Nevertheless, it might prove troublesome for callers who do not mind receiving undefined
values.
Could there be an alternative solution apart from these choices?