generated at
noUncheckedIndexedAccess
以下2つに対して、 undefiend のチェックを強制する
index signatureで定義されたpropertyへのアクセス
配列のindex access





ts
type Hoge = { speed: 'fast' | 'medium' | 'slow'; [key: string]: string; }; const hoge: Hoge = { speed: 'fast', piyo: 'sss', }; const speed = hoge.speed; // string const piyo = hoge['piyo']; // string|undefined. 実際はstring const fuga = hoge['fuga']; // string|undefined. 実際はundefined
これは、noPropertyAccessFromIndexSignatureが無効な場合にもちゃんと |undefined になる
ts
const piyo = hoge.piyo; // string|undefined. 実際はstring
index accessの例
ts
const hoge = [0, 1, 2]; const _1 = hoge[1]; // number|undefined. 実際はnumber const _3 = hoge[3]; // number|undefined. 実際はundefined
ちなみにtupleなら |undefined にはならない
ts
const hoge = [0, 1, 2] as const; const _1 = hoge[1]; // 1 const _3 = hoge[3]; // error



if(hoge.length > 0) を確認した時に、
hoge[0] を、 T|undefiend ではなく、 T にしてほしい
しかし、これは以下のようなコーナーケースが存在するため安全でないので無理
ts
let arr: number[] = []; arr[1] = 42; console.log(arr.length); // 2。 なので arr.length>0 は true console.log(arr[0]); // undefined




参考