I am running a lambda function predicate over a list of values to find the first value matching the predicate. However, in addition to finding the right value, I want to store the result of an internal calculation in the lambda function for later.
Simplified example:
let helper: number | undefined = undefined;
const array = [1, 2, 3];
const result = array.find((v) => {
helper = v % 2;
return helper === 0;
});
console.log({ helper, result });
if (helper !== undefined) {
console.log(helper.toExponential());
}
Here, result
should be the first value matching the predicate and helper
should store the internal calculation, which I want to do something with later on. In order to consider the case where no value matches the predicate, I defined the type of helper
to be number
or undefined
and check afterwards, if helper
is a number before I do anything with it.
At runtime everything works as expected and the output is:
{ "helper": 0, "result": 2 }
"0e+0"
However, TypeScript complains:
Property 'toExponential' does not exist on type 'never'.
That is, TypeScript does not see the reassignment of helper
within the lambda function. Because it does not see it, it deduces that the type of helper
can be simplified to undefined
.
How can I make TypeScript aware that I am reassigning a variable in a lambda function?
3