JavaScript 加了 ?. 還是 TypeError?檢查中間值、括號與函式
本文目錄
data?.profile.name 仍然拋出 TypeError 時,先看缺的是 data 還是 profile。?. 檢查的是緊接在它左側的值;當 data 存在、profile 缺失,後面的 .name 仍會讀取 undefined。
修正方式取決於契約:profile 可以缺就用 data?.profile?.name;profile 必須存在就驗證資料並明確報錯。盲目在每一層加上 ?.,會讓必要欄位的錯誤也變成空值。MDN optional chaining
用三組輸入看清 optional chaining 的保護範圍
把以下程式存成 optional-chain.mjs,以 node optional-chain.mjs 執行:
import assert from 'node:assert/strict';
const absent = null;const missingProfile = {};const complete = { profile: { name: '小林' } };
assert.equal(absent?.profile.name, undefined);assert.throws(() => missingProfile?.profile.name, TypeError);assert.equal(missingProfile?.profile?.name, undefined);assert.equal(complete?.profile.name, '小林');
assert.throws(() => (absent?.profile).name, TypeError);assert.equal((absent?.profile)?.name, undefined);第一行斷言的 absent 是 null,整條連續鏈直接短路。第二行的物件存在,所以繼續讀到缺失的 profile 才失敗。最後兩行則展示括號的差異:(absent?.profile) 已求值為 undefined,括號外 .name 是另一個存取動作,必須自行處理空值。
重構時把一條鏈拆成暫存變數,也應重新看待後續存取:const profile = data?.profile 允許 profile 為 undefined,下一行 profile.name 仍有同樣風險。ESLint 的 no-unsafe-optional-chaining 可攔截多種短路後仍會出錯的寫法;lint 能提供線索,資料是否可缺仍由契約決定。
?.() 只處理不存在的函式
選用 callback 時,callback?.() 可以處理 nullish;如果外部資料把 callback 填成字串,呼叫仍然會失敗。
import assert from 'node:assert/strict';
assert.equal(undefined?.(), undefined);const options = { onSave: 'disabled' };assert.throws(() => options.onSave?.(), TypeError);
function notify(onSave, value) { if (onSave == null) return; if (typeof onSave !== 'function') { throw new TypeError('onSave 必須是函式、null 或 undefined'); } onSave(value);}
let received;notify(undefined, '忽略');notify((value) => { received = value; }, '已儲存');assert.equal(received, '已儲存');assert.throws(() => notify('disabled', '資料'), TypeError);這裡把「未提供 callback」與「提供錯誤型別」分開,讓錯誤在入口就能定位。相同原則也適用於 API 回應:data?.items?.map(...) 仍無法保證 items 是陣列,應先用 Array.isArray() 驗證必要的集合型別。
預設值要放在資料規則允許的位置
顯示名稱可以缺時,可用 data?.profile?.name ?? '未提供姓名'。?? 只處理 nullish,因此空字串會保留;若產品規則把空白姓名也視為缺值,要另行檢查字串內容。
如果 profile 是完成登入後的必要欄位,則在 API 資料進入畫面前檢查其形狀,失敗時呈現可辨識的錯誤。這樣比讓所有欄位都顯示「未提供」更容易發現後端格式變動。若你處理的是解構預設值遇到 null,可接著看解構預設值與 null 的差異。
本文兩段程式各自以 Node.js v24.13.0 執行斷言。測的是語言語意,未執行特定框架元件或瀏覽器回歸。
參考資料: