⚠ WARNING! ⚠
IT IS WIDELY CONSIDERED BAD PRACTICE TO MODIFY NATIVE PROTOTYPES, mainly because it might change the code — specially its behavior — other programmers depend on.
See Why is extending native objects a bad practice? for more information. In what follows I'm going to show how to do it, but this is not meant to say that you should do it. A standalone isEmpty()
function would work just as well, and is far less controversial.
Do check out @Dimava's answer as well, as he shows yet another way of doing this.
If you want to append a getter to an existing object, then you need to use the Object.defineProperty()
method.
Your example could therefore look like:
// declare global { // <-- needed within modules
interface Object {
isEmpty: boolean;
}
// }
Object.defineProperty(Object.prototype, "isEmpty", {
configurable: true,
get() {
return Object.keys(this).length === 0;
},
});
As for Array
s, you could simply do the same but with Object.defineProperty(Array.prototype, ...)
.
And you can verify that it works as desired:
const a = { z: 1 };
console.log(a.isEmpty) // false
const b = {};
console.log(b.isEmpty) // true
Playground link to code