【问题标题】:Define prototype function with typescript用打字稿定义原型函数
【发布时间】:2017-01-20 22:11:05
【问题描述】:

当我尝试定义原型函数时,我得到:

错误 TS2339:类型上不存在属性“applyParams” “功能”。

Function.prototype.applyParams = (params: any) => {
     this.apply(this, params);
}

如何解决这个错误?

【问题讨论】:

  • 试试这个:stackoverflow.com/a/28020863/1142380 我认为你不需要“prototype.”部分
  • @ToastyMallows 但随后出现错误 TS2339:“FunctionConstructor”类型上不存在属性“applyParams”。即使使用接口 FunctionConstructor { applyParams(params: any): any; }

标签: typescript prototype


【解决方案1】:

.d.ts 文件中定义名为Function 的接口上的方法。这将导致它使用全局Function 类型为declaration merge

interface Function {
    applyParams(params: any): void;
}

您不想使用箭头函数,这样this 就不会被绑定到外部上下文。使用正则函数表达式:

Function.prototype.applyParams = function(params: any) {
    this.apply(this, params);
};

现在这将起作用:

const myFunction = function () { console.log(arguments); };
myFunction.applyParams([1, 2, 3]);

function myOtherFunction() {
    console.log(arguments);
}
myOtherFunction.applyParams([1, 2, 3]);

【讨论】:

  • 我也尝试使用接口,但仍然出现错误。我试过接口函数和接口函数构造器
  • @Alexandre 你在使用外部模块吗?在定义文件(.d.ts 文件)中定义接口并在您的应用程序中引用它
  • @Alexandre 你可以看到这个工作here
  • 感谢 .d.ts 的建议
猜你喜欢
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 2019-08-03
  • 1970-01-01
  • 2016-09-04
  • 2021-12-15
相关资源
最近更新 更多