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