Typescript scope augmentation Object

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 answer

  • answered 2019-09-15 22:48 skovy

    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