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
Define prototype function with typescript
提问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 Function
in a .d.ts
file. This will cause it to declaration mergewith the global Function
type:
Function
在.d.ts
文件中命名的接口上定义方法。这将导致它与全局类型声明合并Function
:
interface Function {
applyParams(params: any): void;
}
And you don't want to use an arrow function so that this
won'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]);