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?
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. 1. A function definition specifies what and how a specific task would be done.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
A function prototype is a definition that is used to perform type checking on function calls when the EGL system code does not have access to the function itself. A function prototype begins with the keyword function, then lists the function name, its parameters (if any), and return value (if any).
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With