初級 › 非nullアサーション(!)がコンパイラを騙して実行時エラーになる › パターン4
非nullアサーション(!)がコンパイラを騙して実行時エラーになる
変数名の後ろに!を付ける非nullアサーションは、「この値はnull/undefinedではない」とコンパイラに約束する構文です。
1 function loud(s: string): string { 2 return s.toUpperCase(); 3 } 4 const arr: string[] = ["a"]; 5 const t: string | undefined = arr[_]; ^ 6 console.log(loud(t!));
main.ts:2
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
空欄を埋めてコンパイルを通す
arr[9]は範囲外なのでundefinedです。t!は実行時の値までは変えないため、例外が起きます。
次の問題