1

I want to extend the Object methods creating "isEmpty".

// typings/object.d.ts

declare global {
    interface Object {
        isEmpty(): boolean;
    }
}

Object.prototype.isEmpty = function (this: Object) {
    for (let key in this) {
        if (this.hasOwnProperty(key)) {
            return false;
        }
    }

    return true;
};

and then I'd like to use it in my source code with:

let myEmptyDict = {};
let myFullDict = {"key": "value"};

console.log(myEmptyDict.isEmpty()); // true
console.log(myFullDict.isEmpty()); // false

It looks like isEmpty is not defined, how can I solve it? I'm Using Typescript 3.6.2.

1 Answers1

0

What you have is correct, with a slight addition. This GitHub issue and this Stack Overflow answer have a few more details.

export {}; // ensure this is a module

declare global {
  interface Object {
    isEmpty(): boolean;
  }
}

Object.prototype.isEmpty = function(this: Object) {
  for (let key in this) {
    if (this.hasOwnProperty(key)) {
      return false;
    }
  }

  return true;
};

let myEmptyDict = {};
let myFullDict = { key: "value" };

console.log(myEmptyDict.isEmpty()); // true
console.log(myFullDict.isEmpty()); // false

TypeScript Playground

skovy
  • 5,430
  • 2
  • 20
  • 34
  • Same, I get: `Uncaught TypeError: myEmptyDict.isEmpty is not a function`. Note: I put this in a typings folder and then used in a component. – Matteo Martinelli Sep 16 '19 at 19:49
  • Note: The referenced Typescript Playground doesn't work due to "Executed JavaScript Failed: Unexpected token 'export' ". To fix, navigate to TSConfig -> Module and change to `CommonJS`. Not sure if you can update the Playground accordingly @skovy? – Woodz Jun 22 '21 at 03:50