Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array as arguments in TypeScript

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?

like image 749
langtu Avatar asked Dec 07 '13 15:12

langtu


People also ask

How do you pass an array as an argument to a function in JavaScript?

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.

How do you pass an array in node?

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.

How do you pass a function as a parameter in TypeScript?

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.

How do you define an array of objects in TypeScript?

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!


2 Answers

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); } 
like image 54
Rick Love Avatar answered Sep 19 '22 19:09

Rick Love


Use Function.prototype.apply:

T.m1.apply(this, args);

Where T is the enclosing class of m1.

like image 22
user703016 Avatar answered Sep 20 '22 19:09

user703016