LoginSignup
4
3

TypeScriptの非nullアサーション演算子(!)について

Posted at

非nullアサーション演算子とは?

nullアサーション演算子(!)は、その直前のオブジェクトがnullまたはundefinedでないことをTypeScriptにアサート(主張)します。

let result = doSomething();  // doSomething could possibly return null or undefined.
const item = result!;

ここで注意すべきは、非nullアサーション演算子はあくまでコンパイル時のチェックをパスさせるためのものであり、実行時にnullundefinedが入らないことを保証するわけではありません。

いつ非nullアサーション演算子を使うべきか?

nullアサーション演算子の使用は注意が必要です。実行時にnullまたはundefinedが発生すると、アプリケーションはクラッシュする可能性があります。

nullアサーション演算子は「絶対にそれがnullまたはundefinedではない」という強い確信があるとき、そしてその確信がテストで裏付けられている場合等に使用する必要があります。

確信できない場合は、他の安全な手段であるnullチェックやOptional chaining(?.)などを選択することが推奨されているようです。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3