55

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?

2 Answers 2

141

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this probably didn't work when the question was first asked. But this is the best way now.
23

Use Function.prototype.apply:

T.m1.apply(this, args);

Where T is the enclosing class of m1.

3 Comments

Yes, passing this in this case will make this within m1 refer to object of outer context (m2). Still need a way to refer to this of m1 within m1.
I'm using 0.9.5, but my sample is incorrect. Actually, my code is A.m1() and B.m2(), so I fixed by call m1.apply(A,args), and it works great. Thank you again!
Not use this method. It's javascript, not typescript. Use the response by Rick Live :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.