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?

Alexandre
  • 3,088
  • 3
  • 34
  • 53
  • Try this: http://stackoverflow.com/a/28020863/1142380 I don't think you need the "`prototype.`" part – ToastyMallows Jan 20 '17 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; } – Alexandre Jan 20 '17 at 22:19

1 Answers1

46

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]);
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • I also tried to use an interface and it still get the error. I tried interface Function and interface FunctionConstructor – Alexandre Jan 20 '17 at 22:22
  • @Alexandre are you using external modules? Define the interface in a definition file (*.d.ts* file) and reference that in your application – David Sherret Jan 20 '17 at 22:25
  • 1
    @Alexandre you can see this working [here](https://www.typescriptlang.org/play/#src=interface%20Function%20%7B%0D%0A%20%20%20%20applyParams(params%3A%20any)%3A%20void%3B%0D%0A%7D%0D%0A%0D%0AFunction.prototype.applyParams%20%3D%20function%20(params%3A%20any)%20%7B%0D%0A%20%20%20%20this(...params)%3B%0D%0A%7D%3B%0D%0A%0D%0Aconst%20func%20%3D%20function%20()%20%7B%20console.log(arguments)%3B%20%7D%3B%0D%0Afunction%20myOtherFunc()%20%7B%0D%0A%20%20%20%20console.log(arguments)%3B%0D%0A%7D%0D%0A%0D%0Afunc.applyParams(%5B1%2C%202%2C%203%5D)%3B%0D%0AmyOtherFunc.applyParams(%5B1%2C%202%2C%203%5D)%3B) – David Sherret Jan 20 '17 at 22:39
  • 2
    Thanks for the .d.ts advice – Alexandre Jan 20 '17 at 22:50
  • 1
    @DavidSherret "*Define the interface in a definition file (.d.ts file)*", could you elaborate on how to do that? – Sebastian Nielsen Apr 18 '22 at 08:35