typescript 用打字稿定义原型函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41773168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:33:07  来源:igfitidea点击:

Define prototype function with typescript

typescriptprototype

提问by Alexandre

When I try to define a prototype function, I get:

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

error TS2339: Property 'applyParams' does not exist on type 'Function'.

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

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

How to solve this error?

如何解决这个错误?

回答by David Sherret

Define the method on an interface named Functionin a .d.tsfile. This will cause it to declaration mergewith the global Functiontype:

Function.d.ts文件中命名的接口上定义方法。这将导致它与全局类型声明合并Function

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

And you don't want to use an arrow function so that thiswon't be bound to the outside context. Use a regular function expression:

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

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

Now this will work:

现在这将起作用:

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

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