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

オプショナルチェイニングでもTypeErrorになる3つの境界:階層・括弧・関数をNode.jsで実測

2
Posted at

user?.profile.name と書いても、profile が null なら例外になります。?. が確認するのは、その記号の左側の値です。さらに、括弧で式を区切ると短絡の範囲も変わります。

Claude Code の生成コードも、欠ける値と ?. の位置を対応させて確認します。今回は階層・括弧・関数呼び出しの3点を比較しました。

検証環境:macOS 27.2.1、Node.js v24.22.1。各ブロックを独立実行しました。ブラウザ、Windowsでは試していません。

1. 欠ける階層ごとに確認する

const inputs = [null, { profile: null }, { profile: { name: "佐藤" } }];
for (const user of inputs) {
  try {
    console.log("one:", user?.profile.name);
  } catch (error) {
    console.log("one:", error.name);
  }
  console.log("two:", user?.profile?.name);
}

出力:

one: undefined
two: undefined
one: TypeError
two: undefined
one: 佐藤
two: 佐藤

user が null の場合、user?.profile.name は連続したチェーンの残りを評価せず、undefined を返します。しかし user が存在して profile が null の場合、最初の確認は通過するため、続く .name で例外になります。

user?.profile?.name なら、user と profile の両方を確認できます。確認対象は null と undefined で、空文字や 0 ではありません。

必須の profile まで省略可能にするかは別判断です。必須項目なら入力検証でエラーにする方針もあります。

2. 括弧の後ろのアクセスは別に考える

const user = null;
console.log(user?.profile.name);
try {
  console.log((user?.profile).name);
} catch (error) {
  console.log(error.name);
}
console.log((user?.profile)?.name);

出力:

undefined
TypeError
undefined

(user?.profile) 自体の結果は undefined です。括弧の外にある .name は、その結果から通常のプロパティアクセスを行うため例外になります。中間変数へ分割した場合も、後続のアクセスに自動で保護が付くわけではありません。欠損を許すなら、取り出した変数に対しても ?.name と書きます。

3. 関数が存在しても、呼べるとは限らない

for (const onSave of [undefined, () => "保存", "save"]) {
  try {
    console.log(onSave?.());
  } catch (error) {
    console.log(error.name);
  }
}

出力:

undefined
保存
TypeError

onSave?.() は、値が null / undefined なら呼び出しを飛ばします。値があっても関数ではない場合は例外になります。

任意のコールバックを受け取る設計で、関数以外も入力され得るなら、たとえば if (typeof onSave === "function") onSave(); と型を確認できます。一方、関数以外を渡すこと自体がバグなら、その誤りを例外として検知する設計もあります。

AIに修正を頼むときの確認項目

  • 欠損してよい階層はどこか。必須項目の不備を隠していないか。
  • 括弧や中間変数の後にも、欠損値への通常アクセスが残っていないか。
  • 任意の関数なのか、型の異なる値も受け入れる設計なのか。

AIには「省略可能な値と必須の値を分け、欠損と型違いを別々に検証して」と条件を伝えます。

仕様の参照:ECMAScript Optional Chains。


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

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