Ale*_*dre 10 prototype typescript
当我尝试定义原型函数时,我得到:
错误TS2339:属性'applyParams'在'Function'类型中不存在.
Function.prototype.applyParams = (params: any) => {
this.apply(this, params);
}
Run Code Online (Sandbox Code Playgroud)
如何解决这个错误?
Dav*_*ret 19
Function在.d.ts文件中指定的接口上定义方法.这将导致它声明与全局Function类型合并:
interface Function {
applyParams(params: any): void;
}
Run Code Online (Sandbox Code Playgroud)
并且您不希望使用箭头函数,因此this不会绑定到外部上下文.使用常规函数表达式:
Function.prototype.applyParams = function(params: any) {
this.apply(this, params);
};
Run Code Online (Sandbox Code Playgroud)
现在这将工作:
const myFunction = function () { console.log(arguments); };
myFunction.applyParams([1, 2, 3]);
function myOtherFunction() {
console.log(arguments);
}
myOtherFunction.applyParams([1, 2, 3]);
Run Code Online (Sandbox Code Playgroud)