Enabling the setting noUncheckedIndexedAccess
to true
in Typescript signifies that the possibility of array access going out of bounds is always considered. As a result, your array type will be interpreted as:
((number | undefined)[] | undefined)[]
When accessing arr[x]
, it may return a value that is potentially undefined (xxx | undefined
). Due to the intricacies in tracking changes to elements within arrays, Typescript is unable to definitively determine whether the array arr
has been modified between the checks of if (arr[x])
and the actual access of arr[x]
. Therefore, it cannot confidently assert that arr[x]
is not undefined.
In cases where a constant or literal value like arr[0]
is passed in, Typescript assumes that this value remains unchanged after if (arr[0])
, which may not always hold true. An example where this oversight can lead to runtime errors is shown below:
const arr: number[][] = [[], [], []];
if (arr[0]) {
arr.length = 0;
arr[0][0] = 42; // Cannot set properties of undefined (setting '0')
}
Regardless of whether Typescript assumes the presence of undefined or not, its judgement is not foolproof. Hence, it tends to provide a more conservative estimate, leading to the current behavior.
If you are confident that your array accesses will not exceed bounds, the use of !
(arr[x]![y]
) can be employed to bypass compile-time linting.