noUncheckedIndexedAccess
以下2つに対して、 undefiend
のチェックを強制する
配列のindex access
tstype 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
tsconst piyo = hoge.piyo; // string|undefined. 実際はstring
index accessの例
tsconst hoge = [0, 1, 2];
const _1 = hoge[1]; // number|undefined. 実際はnumber
const _3 = hoge[3]; // number|undefined. 実際はundefined
ちなみにtupleなら |undefined
にはならない
tsconst 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
にしてほしい
しかし、これは以下のようなコーナーケースが存在するため安全でないので無理
tslet arr: number[] = [];
arr[1] = 42;
console.log(arr.length); // 2。 なので arr.length>0 は true
console.log(arr[0]); // undefined
参考