First off, please note that what you are doing is not destructuring - it is called object spread.
Spreading objects only takes ownProperty
s into account. Error
instances don't have any non-inherited properties. That is why console.log(error)
also outputs {}
:
const error = new Error('Error test');
const freeError = {...error};
console.log(error, freeError);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Properties
Because inherited properties are not part of the spread result object, error
does have a message property (inherited from its prototype), whereas freeError
does not have it.
Check this example:
const str = new String('Hello world');
const freeStr = { ...str };
console.log(str.length); // 11
console.log(freeStr.length); // undefined
As you can see str
does have a length
property (inherited from the String
prototype
), whereas freeStr
does not have it (for the same reason as in your example).
Again, see MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_instances