27.TypeScript|Optional Chaining

前回に引き続きTypeScriptの?関連について。

Optional Chainingは、?.という構文のこと。
最も基本的な用法はプロパティアクセスの.の代わりに?.を使うもの。

You might find yourself using ?. to replace a lot of code that performs repetitive nullish checks using the && operator.

// Before
if (foo && foo.bar && foo.bar.baz) {
    // ...
}

// After-ish
if (foo?.bar?.baz) {
    // ...
}
  • Nullish Coalescing(Null合体演算子

The nullish coalescing operator is another upcoming ECMAScript feature that goes hand-in-hand with optional chaining, and which our team has been involved with championing in TC39.

You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined. When we write code like

let x = foo ?? bar();

this is a new way to say that the value foo will be used when it’s “present”; but when it’s null or undefined, calculate bar() in its place.

Again, the above code is equivalent to the following.

let x = (foo !== null && foo !== undefined) ?
    foo :
    bar();

www.typescriptlang.org

注意点としては、【null:明示的に未設定/undefined:valueが存在しないこと】はチェックしているが、【空文字や0】は考慮されていないこと。