用打字稿定义原型函数 [英] Define prototype function with typescript

查看:55
本文介绍了用打字稿定义原型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

错误 TS2339:类型上不存在属性applyParams"'函数'.

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

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

如何解决这个错误?

推荐答案

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

Define the method on an interface named Function in a .d.ts file. This will cause it to declaration merge with the global Function type:

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

并且您不想使用箭头函数以便 this 不会绑定到外部上下文.使用正则函数表达式:

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:

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]);

这篇关于用打字稿定义原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆