noUncheckedIndexedAccess
TypeScript v4.1から
以下2つに対して、undefiendのチェックを強制する
index signatureで定義されたpropertyへのアクセス
配列のindex access
PR
index signatureでの例
code: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になる
code:ts
const piyo = hoge.piyo; // string|undefined. 実際はstring
index accessの例
code:ts
const hoge = 0, 1, 2;
const _1 = hoge1; // number|undefined. 実際はnumber
const _3 = hoge3; // number|undefined. 実際はundefined
ちなみにtupleなら|undefinedにはならない
code:ts
const hoge = 0, 1, 2 as const;
const _1 = hoge1; // 1
const _3 = hoge3; // error
if(hoge.length > 0)を確認した時に、
hoge[0]を、T|undefiendではなく、Tにしてほしい
Flow-sensitive Typing
しかし、これは以下のようなコーナーケースが存在するため安全でないので無理
code:ts
let arr: number[] = [];
arr1 = 42;
console.log(arr.length); // 2。 なので arr.length>0 は true
console.log(arr0); // undefined
https://github.com/microsoft/TypeScript/issues/42909
https://github.com/microsoft/TypeScript/issues/51988
参考
noUncheckedIndexedAccess | TypeScript入門『サバイバルTypeScript』
https://zenn.dev/uhyo/articles/ts-array-length