typescript - 用 typescript 定义原型(prototype)函数

标签 typescript prototype

当我尝试定义原型(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/

相关文章:

node.js - 使用 express.js 和 TypeScript 的 Node Js 路由

typescript - 泛型:TS2345 'T[keyof T]' 类型的参数不可分配给 'Date' 类型的参数,其中 <T extends {}>

javascript - 函数声明中指定的基于原型(prototype)的继承

c - int main() 有什么问题?

generics - Typescript 无法检测索引签名中泛型方法的参数类型

html - 如何在我的覆盖 div 中垂直居中我的跨度?

typescript - 后续的属性声明必须具有相同的类型。属性字符串应该是类型 () => string

jquery - Jasmine 在原型(prototype)方法上的 spy toHaveBeenCalled 的问题

c++ - hpp/cpp split with global function : Multiple definition of . .. 错误

javascript - 是否可以将对象原型(prototype)上的方法组织到 namespace 中?