打字稿范围扩展对象

时间:2019-09-15 22:15:41

标签: typescript

我想扩展创建“ 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;
};

然后我想在我的源代码中使用它:

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

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

看来isEmpty没有定义,我该如何解决? 我正在使用打字稿3.6.2。

1 个答案:

答案 0 :(得分:0)

您所拥有的是正确的,还有一点点补充。这个GitHub issue和这个Stack Overflow answer还有更多细节。

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