当我尝试定义原型(prototype)函数时,我得到:
error TS2339: Property 'applyParams' does not exist on type 'Function'.
Function.prototype.applyParams = (params: any) => {
this.apply(this, params);
}
如何解决这个错误?
最佳答案
在 .d.ts
文件中的名为 Function
的接口(interface)上定义方法。这将导致它 declaration merge使用全局 Function
类型:
interface Function {
applyParams(params: any): void;
}
并且您不想使用箭头函数,这样 this
就不会绑定(bind)到外部上下文。使用正则函数表达式:
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]);
关于typescript - 用 typescript 定义原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41773168/