Skip to content

TypeScript オプショナルチェーン

ts
const human = {
  age: 25,
  firstName: Math.random() > 0.5 ? 'Alice' : null,
}

console.log(human.firstName?.toUpperCase())

 オプショナルチェーン(?.)を使用すると、nllでない限りメソッドを呼び出すという条件付きの実行が可能になる。この方法により、null参照エラーや未定義のプロパティのアクセスによって発生する一般的なエラーをランタイムで防ぐことが可能。

Result

sh
undefined

or

sh
ALICE