Consider this example:
export function fn(arg: string): void;
export function fn(arg: number): void;
export function fn(arg: any) {
console.log(arg);
}
So, fn can be called either with a string, or a number.
fn('hello!');
fn(42);
So far, so good.
But then fn is executed in a different place:
function fn2(arg2: string | number) {
fn(arg2);
}
In this case TypeScript complains:
No overload matches this call. Overload 1 of 2, '(arg: string): void', gave the following error.
Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'. Overload 2 of 2, '(arg: number): void', gave the following error. Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'.ts(2769)
index.tsx(3, 17): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
Can someone help me understand what's going on here?
You can add another overload
export function fn(arg: string): void;
export function fn(arg: number): void;
export function fn(arg: any): void;
export function fn(arg: any) {
console.log(arg);
}
fn('hello!');
fn(42);
function fn2(arg2: string | number) {
fn(arg2);
}
Playground
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