I have two methods:
static m1(...args: any[]) {
//using args as array ...
}
static m2(str: string, ...args: any[]){
//do something
//....
//call to m1
m1(args);
}
The call to m1(1,2,3)
works as expect. However, the call m2("abc",1,2,3)
will pass to m1([1,2,3])
, not as expect: m1(1,2,3)
.
So, how to pass args
as arguments when make call to m1
in m2
?
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
stringify the array (or any arbitrary JSON object really) on the server and then JSON. parse it on the client. So you need to change the client side code little bit.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!
Actually, using the ...
again when calling the method will work.
It generates the apply call for you in javascript.
static m1(...args: any[]) { //using args as array ... } static m2(str: string, ...args: any[]){ //do something //.... //call to m1 // m1(args); // BECOMES m1(...args); }
Use Function.prototype.apply:
T.m1.apply(this, args);
Where T is the enclosing class of m1
.
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