const f = (x: number) => { }
const a : (number | undefined)[] = [1,undefined,3];
for (let i = 0; i < a.length; i ) {
if (a[i]) {
f(a[i]);
}
}
In the example above, a
is an array that can hold an element which can be either number of undefined.
In the loop, I want to only access the element if it is not undefined. My understanding is that if (a[i])
would filter every undefined values (also 0 too, but let's not think of that here).
So I thought the typescript would think the type of a[i]
inside the if
would be simply number
. But if I get this error when calling f
.
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.
'x' is declared but its value is never read.
Why is the type of a[i]
cannot be deduced to number
with the if
check above?
CodePudding user response:
The below code will work fine, it is because typescript does not deduce what type a[i] would result in, in the if condition itself. Creating a variable and then checking the same would work. This is a known issue as you can access both arrays and object with the square bracket [].
const f = (x: number) => { }
const a : (number | undefined)[] = [1,undefined,3];
for (let i = 0; i < a.length; i ) {
let j = a[i];
if (j) {
f(j);
}
}