LoginSignup
0
0

More than 3 years have passed since last update.

【Typescript】オブジェクトの要素チェック

Posted at

はじめに

最近Typescriptの勉強を始めました。ちょこちょこ便利だなと思った書き方を覚書していきます。今回はOptional Chainingについてです。

Javascriptの場合

const fetchedPostData = {
  id: "p1",
  author: { name: "MIKE", age: "22" },
};

こんな感じのオブジェクトの要素を取り出したいなーと思った時、エラーを回避するために

if (fetchedPostData) {
  if (fetchedPostData.author) {
    console.log(fetchedPostData.author.name);
  }
}

とか、もう少しスマートに書くなら

if (fetchedPostData && fetchedPostData.author)
  console.log(fetchedPostData.author.name);

と書きます。

Typescriptの場合

?を使ってさらに潔にかけます。

console.log(fetchedPostData?.author?.name);

最後に

美しい・・・

また新しいこと覚えたら書きます。

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