2
1

More than 3 years have passed since last update.

Javascript/TypescriptでOptional Chainingが使えるようになるらしい。

Last updated at Posted at 2020-05-05

ECMAScript2020の新機能の一つに、Optinal Chainingが入っていました。
これはSwiftなどではすでに使える構文で、値が入っているかどうかわからない変数にアクセスする場合、手前に?をつけておくことでnullpointerExceptionなどのエラーが発生しないようすることができる機能です。

例えば、foo.barの中にあるbaz関数を実行したい。でも、fooの中にbarが入っていない事がある場合、記述するプログラムはそのことを考慮して以下のようになります。

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

これが、Optional Chainingを使うことによって以下の記述となります。

let x = foo?.bar.baz();

Typescript3.7のリリースノートを見ると、Typescriptではすでにこの記法は利用できるようになっている様です。

是非活用して行きたいですね。

Typescript3.7 リリースノート

ECMAScript2020 What's new

2
1
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
2
1