LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript】Object is possibly 'null'

Posted at

エラー内容

例えば、

name: `${message.member.displayName}`

のように、オブジェクトのメンバを呼び出そうとすると
スクリーンショット 2023-01-17 135744.png
とエラーが返ってくる。

解決策

1. "!"を付ける

name: `${message.member!.displayName}`

とすれば、エラーは出なくなる。"!"は変数が必ずnon-nullの時につける演算子で、その変数がnullである可能性を考慮しなくなる。この例だとmessage.memberが絶対にnon-nullでなければならない。
ESlintを使っている場合、以下のような警告文が出る。
スクリーンショット 2023-01-17 140607.png

2. "?"を付ける(おススメ)

name: `${message.member?.displayName}`

"?"演算子は、変数がnull(またはundefined)の時に、エラーを出す代わりに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