オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐ
ネストしたプロパティの途中がnullやundefinedかもしれない場合、通常のドットアクセスではTypeErrorになります。?.を使うと、途中がnull/undefinedのときに例外を投げず、undefinedを返して処理を続けられます。
エラーメッセージの読み方
main.js:2
main.js- ファイル名
2- 行番号 — 実際にクラッシュした行
TypeError- 例外クラス — 何が起きたか。ここを検索するのが最短です
Cannot read properties of null (reading 'name')- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 const user = { profile: null }; 2 console.log(user.profile .name); ^
main.js:2
console.log(user.profile.name);
^
TypeError: Cannot read properties of null (reading 'name')
profileがnullのままドットアクセスするとエラーになります。?.を使うと、profileがnull/undefinedのときは例外を投げずundefinedを返します。
直し方: (空) を ? にします。
広告
広告スロット(未設定)
パターン2
1 const config = { settings: null }; 2 console.log(config.settings .theme); ^
main.js:2
console.log(config.settings.theme);
^
TypeError: Cannot read properties of null (reading 'theme')
settingsがnullの場合、?.を挟むことで安全にthemeへアクセスできます。
直し方: (空) を ? にします。
パターン3
1 const response = { data: null }; 2 console.log(response.data .items); ^
main.js:2
console.log(response.data.items);
^
TypeError: Cannot read properties of null (reading 'items')
dataがnullでもitemsに直接アクセスしようとするとエラーになります。?.でnullの可能性に安全に対処できます。
直し方: (空) を ? にします。
よくある誤解
「存在確認は毎回if文で書くしかない」という思い込みは、?.を知らないと起きがちです。ネストが深いほど毎回のnullチェックは冗長になり、?.を使えば1箇所で安全に済みます。
まとめ
オプショナルチェイニング(?.)でnull/undefinedアクセスのエラーを防ぐは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。