2

I would like to create a method that accepts either an array of strings, or allow strings to be supplied as a rest parameter. When I try this, I get a compiler warning that "Overload Signature Is Not Compatible".

As the rest parameter results in a string array, shouldn't this be okay?

class Example {
    test(...strArray: string[]);
    test(strArray: string[]);
    test(strArray: string[]) {
        alert(strArray.length.toString());
    }
}

2 Answers 2

3

Rest arguments get packed into an array at the function body, not at the call sites. The (...strArray: string[]) overload only results in the first parameter being an array when it is the implementation signature, because the codegen for rest args is what packages the arguments into an array for you. The existence of other call signatures doesn't influence the codegen for the implementation signature.

In your example, if someone invoked test('hi'), strArray would be 'hi', not ['hi'].

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent - and it has given me an idea for how to work around it! Thanks.
1

Potentially can be, but the compiler takes the literal meaning of [string1,string2] vs. string1,string2 which are not compatible. So the only option

class Example {
    test(...strArray: string[]);
    test(strArray: string[]);
    test(strArray: any){
        alert(strArray.length.toString());
    }
}

You can always just use ['a','b'] to wrap the case for rest parameters:

1 Comment

Good answer - this would result in a length of 1 if rest parameters were used as the first argument would be assumed to be strArray.

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.