0

I have a function in Typescript with overloads as follows:

function test(atts?: {[key: string]: string}, ...children: string[]): void;
function test(atts?: {[key: string]: string}): void;
function test(...children: string[]): void; //Overload 3
function test(): void;
function test(arg1?: {[key: string]: string} | string[], ...arg2: string[]) {
  console.log(arg1, arg2)
}

However, I keep being told that overload 3 is not compatible with it's implementation signature. How do I fix this error?

I've looked at other answers, but am still struggling to make this work. I think it has something to do with arg2 being potentially undefined, which makes it incompatible with the third overload. But rest parameters can't be undefined, so I'm not sure how to implement this logic if that's the case.

1 Answer 1

1

You expect arg1 in the implementation to possibly be a string, not a string[], right? The third call signature supports something like test("hey", "you", "there")... in which case, arg1 will be "hey" and arg2 will be ["you", "there"].

But you have arg1 as possibly string[], which is not possible. So there's the error. Change it to string and it should work:

function test(atts?: {[key: string]: string}, ...children: string[]): void;
function test(atts?: {[key: string]: string}): void;
function test(...children: string[]): void; 
function test(): void;
function test(arg1?: {[key: string]: string} | string, ...arg2: string[]) {
// ------------------------------------------> ~~~~~~ <--- here
  console.log(arg1, arg2)
}

Playground link to code

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

1 Comment

Oh gotcha! I see now. Thank you!

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.