Flow analysis in TypeScript helps narrow down variable types, but has limitations when it comes to narrowing down arrays with undefined elements:
type T1 = (number | undefined)[]
const myFunc = (arr: T1, index: number) => {
if (arr[index] === undefined) {
return []; // never[]
}
//the type of `arr` remains as T1
let temp = arr[index]; //number | undefined
return temp;
}
It can be challenging to represent the type of arr
after the if
block – should it still be considered as an array of number|undefined, except for that particular dynamic index? Falling back to T1
may be the simplest solution.
A ternary operator may not improve upon this situation significantly.
In contrast, TypeScript shines in narrowing down types for a result
variable within flow control statements:
type T1 = (number | undefined)[]
const myFunc = (arr: T1, index: number) => {
const result = arr[index];
if (result === undefined) {
return []; // never[]
}
//here, the type of `result` is correctly determined as number
return result;
}
While variables like arr
and result
can have their types narrowed down by control flow, expressions like arr[index]
will depend on the types of arr
and index
at that specific point.