javascript エラー「Uncaught TypeError: Cannot destructure property ‘xxx’ of ‘undefined’ as it is undefined.」の解決方法
- 作成日 2022.11.07
- javascript
- javascript

javascriptで、エラー「Uncaught TypeError: Cannot destructure property ‘xxx’ of ‘undefined’ as it is undefined.」が発生した場合の原因と解決方法を記述してます。オブジェクトの分割代入で「undefined」を代入した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 107.0.5304.88
エラー内容
以下の、オブジェクトの分割代入を使用して「undefined」を代入しようとした際に発生。
const { a } = undefined;
エラーメッセージ
Uncaught TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined.
画像

firefox106の場合では、以下のエラーが発生します。
Uncaught TypeError: undefined has no properties
画像

safari15.5では、以下のエラーとなります。
TypeError: Right side of assignment cannot be destructured
画像

原因
分割代入を使用して、直接「undefined」は代入できないため
解決方法
空のオブジェクトを代入して「undefined」とするか、
const { a } = {};
console.log(a); // undefined
オブジェクトを用意して代入します。
const obj = { a : undefined }
const { a } = obj;
console.log(a); // undefined
-
前の記事
Dart 区切り文字を指定してリスト(配列)を連結して文字列に変換する 2022.11.07
-
次の記事
Oracle Database 文字列をUTF-16表記のアスキーコードで取得する 2022.11.07
コメントを書く