3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

✅この記事について

現在TypeScript学習中です!わからなかったことをまとめたので、自分用備忘録を兼ねて記事を作成します。


✅ 概要

オプショナルチェイニング(?.)は、JavaScript/TypeScript の構文で、
null または undefined の可能性があるプロパティに安全にアクセスするための演算子


✅ 書き方と意味

const value = obj?.prop
  • objnull または undefined の場合 → valueundefined になる(エラーにならない)
  • obj が存在すれば obj.prop の値を返す

✅ よくある使用例

1. ネストしたオブジェクトの安全なアクセス

const user = { profile: { name: "Alice" } }

const name = user.profile?.name   // "Alice"
const age = user.profile?.age     // undefined
const city = user.address?.city   // undefined(address がないので安全にスキップ)

2. 配列の要素チェック

const items = []

const firstId = items[0]?.id  // undefined(items[0] が存在しないため)

3. 関数の存在確認と実行

user.printName?.() // 関数があれば呼び出す、なければ無視

✅ よく一緒に使われる構文:Null合体演算子(??

const result = obj?.value ?? "デフォルト値"
  • obj?.valuenull または undefined のとき "デフォルト値" を返す
  • false0 はそのまま使われる(nullish 判定)

❌ よくある間違い(古い書き方)

// エラーになる可能性あり(objがnullの場合)
const value = obj.prop.subprop

✅ メリットまとめ

  • ネストしたオブジェクトの安全な参照ができる
  • 冗長な if&& チェーンを省略できる
  • 配列・関数・オブジェクトすべてに使える
  • コードが読みやすくなる

💡 注意点

  • プロパティアクセス/関数呼び出しのみに使用可能
    • OK: obj?.prop, obj?.[key], func?.()
    • NG: obj?prop, ?.obj.prop など文法誤り
  • オプショナルチェイニングは左側が null / undefined のみを対象としている
3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?