Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 885
Alexandre Avatar asked Jan 20 '17 22:01

Alexandre


People also ask

How do you define a function in TypeScript?

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.

How do you define a function type variable in TypeScript?

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.

What is function prototype with example?

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).


1 Answers

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]);
like image 56
David Sherret Avatar answered Oct 29 '22 09:10

David Sherret