7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeScript の "?." と "!." ってなんだっけ

Last updated at Posted at 2020-08-05

紛らわしい表記シリーズです。
TypeScript書いていると出てくるやつら。

?.: optional chaining
!.: Non-Null Assertion Operator

について。

?. optional chaining

TypeScript ではなく JavaScript の機能です。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Optional_chaining

接続されたオブジェクトチェーンの深くに位置するプロパティの値を、チェーン内の各参照が正しいかどうかを明示的に確認せずに読み込むことを可能にします。

nullだったらさらに先を評価しないで終わりにするためのもの。

let nestedProp = obj.first && obj.first.second;

上記の短縮表記

let nestedProp = obj.first?.second;

覚え方: nullかも?

!. Non-Null Assertion Operator

TypeScriptの機能。

型チェッカーが結論付けられないコンテキストにおいて、そのオペランドが非nullでかつ非undefinedであることをアサートすることができます。

型チェッカーに nullable だった変数を null じゃないよって教えるためのもの。

ポストフィックス式演算子

なので、正確には!単体が Non-Null Assertion Operatorで、. のほうにかかっているわけではなくて、hoge!.fugaだったら hoge の方にかかっているようです。

これは単なるアサーションであり、型アサーションと同じように、あなたは値がnullでないことを確認する責任があることに注意してください。

単なるアサーションなので?.とは本質的に動きが違います。

覚え方: nullじゃない!

7
0
2

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
7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?