27

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?

2
  • Try this: stackoverflow.com/a/28020863/1142380 I don't think you need the "prototype." part Commented Jan 20, 2017 at 22:13
  • @ToastyMallows but then I get error TS2339: Property 'applyParams' does not exist on type 'FunctionConstructor'. Even with interface FunctionConstructor { applyParams(params: any): any; } Commented Jan 20, 2017 at 22:19

1 Answer 1

48

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]);
Sign up to request clarification or add additional context in comments.

5 Comments

I also tried to use an interface and it still get the error. I tried interface Function and interface FunctionConstructor
@Alexandre are you using external modules? Define the interface in a definition file (.d.ts file) and reference that in your application
@Alexandre you can see this working here
Thanks for the .d.ts advice
@DavidSherret "Define the interface in a definition file (.d.ts file)", could you elaborate on how to do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.