【问题标题】:Typescript scope augmentation Object打字稿范围扩大对象
【发布时间】:2019-09-16 06:48:33
【问题描述】:

我想扩展创建“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 没有定义,我该如何解决? 我正在使用 Typescript 3.6.2。

【问题讨论】:

  • 我建议不要在生产中进行猴子补丁;即使可以在打字稿中“输入”

标签: typescript


【解决方案1】:

您所拥有的是正确的,只是稍微添加了一点。这个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

【讨论】:

  • 同样,我得到:Uncaught TypeError: myEmptyDict.isEmpty is not a function。注意:我把它放在一个typings文件夹中,然后在一个组件中使用。
  • 注意:引用的 Typescript Playground 由于“执行的 JavaScript 失败:意外的令牌 'export'”而无法工作。要修复,请导航到 TSConfig -> 模块并更改为 CommonJS。不确定您是否可以相应地更新 Playground @skovy?
猜你喜欢
  • 1970-01-01
  • 2021-09-23
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多