javascript エラー「Uncaught TypeError: Property description must be an object: null」の解決方法

javascript エラー「Uncaught TypeError: Property description must be an object: null」の解決方法

javascriptで、エラー「Uncaught TypeError: Property description must be an object: null」が発生した場合の原因と解決方法を記述してます。「Object.defineProperty」使用時にプロパティにセットする値が記述されていないと発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.88

エラー内容

以下のオブジェクトにプロパティを作成する「Object.defineProperty」を使用したコードで発生。

const obj = {
  'hoge': 1
};

Object.defineProperty(obj, 'foo', null)

エラーメッセージ

Uncaught TypeError: Property description must be an object: null
at Function.defineProperty (<anonymous>)

画像

firefox(バージョン106)では、以下のエラーとなります。

Uncaught TypeError: Property descriptor must be an object, got null

画像

safari(15.5)では、以下のエラーとなります。

TypeError: Property description must be an object.

画像

原因

プロパティ値が「null」となっているため

解決方法

「プロパティ」を記述する

const obj = {
  'hoge': 1
};

Object.defineProperty(obj, 'foo', { value: 2, writable: false });

console.log(obj);
// {hoge: 1, foo: 2}