0
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 1 year has passed since last update.

【TypeScript】オプショナルチェーン

Posted at

内容

TypeScript、JavaScriptのオプショナルチェーンについてふんわりとしか理解していなかったのでメモとしてまとめておきたいと思います

オプショナルチェーンとは??

TypeScriptのオプショナルチェーンは、オブジェクトや配列のプロパティやメソッドが存在するかどうかを確認するための機能です。オプショナルチェーンを使用すると、undefinedやnullの値が混入している場合でも、安全にプロパティにアクセスできます。です。

  • オブジェクトの場合
    以下のようなオブジェクトがあるとします。
const user = {
  name: 'Alice',
  address: {
    street: '123 Main St',
    city: 'New York',
    country: 'USA'
  }
};

ここで、user.ageにアクセスすると、存在しないので当然エラーが発生してしまいます。
そこで使用されるのがオプショナルチェーンです。
userの中に存在するのかチェックするのでuser?.xxxという書き方になります。
console.logで確認してみると、

console.log(user?.age); // undefined

user.ageは存在しないのでundefinedが返ってきます。

このようにコードを簡略化でき、undefinedやnullチェックを手動で行う必要がなくなります。

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