Alexandre
Alexandre

Reputation: 3170

Define prototype function with typescript

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

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

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

How to solve this error?

Upvotes: 27

Views: 55789

Answers (1)

David Sherret
David Sherret

Reputation: 106850

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;
}

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

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

Upvotes: 48

Related Questions