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

プロパティの後ろにつく?は何を意味しているのか?

Posted at

Typescriptで開発していると、以下のようなコードに出会うと思います。

const resultText = data.choices[0]?.message?.content?.trim();

プロパティの後ろにつく?は何気なく使っていましたが、実際何なのよってことでまとめます。

公式では以下。

オプショナルチェーン (?.) (optional chaining) 演算子は、オブジェクトのプロパティにアクセスしたり、関数を呼び出したりします。この演算子を使用してアクセスするオブジェクトまたは呼び出される関数が undefined または null の場合、エラーが発生することなく、式が途中で終了し、undefined と評価されます。

オブジェクト内のプロパティがあるかどうか判定し、なければundefinedを返してくれる優れもの。

オプショナルチェーンの役割

安全なプロパティアクセスを保証したいときに使います。

  • ネストされたプロパティ(choices[0].message.content など)を直接参照すると、途中でオブジェクトが null や undefined の場合にエラー(TypeError: Cannot read property ...)を回避する。
  • プロパティが存在しない場合でもエラーを投げず、安全にundefined を返す。

動作例

ケース 1: 正常なデータ

const data = { choices: [{ message: { content: " Hello World " } }] };
const resultText = data.choices[0]?.message?.content?.trim(); // "Hello World"

ケース 2: プロパティが欠けている場合

const data = { choices: [{}] };
const resultText = data.choices[0]?.message?.content?.trim(); // undefined

ネストされたオブジェクトやメソッドの安全なアクセスを簡単にする便利な演算子です。コードを簡潔にし、予期しないエラーを防ぐため、ぜひ活用してみてください!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?