I am trying to create a function passes its arguments to another function. Both of these functions need to have the same overloads.
function original (a: number): boolean;
function original (a: string, b: string): boolean;
function original (a: number | string, b?: string): boolean {
return true;
}
function pass (a: number): boolean;
function pass (a: string, b: string): boolean;
function pass (a: number | string, b?: string): boolean {
return original(a, b);
}
This does not work.
Argument of type 'string | number' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'.(2345) input.tsx(4, 10): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
Playground
Restrictions on overloadingAny two functions in a set of overloaded functions must have different argument lists. Overloading functions that have argument lists of the same types, based on return type alone, is an error.
There is no real function overloading in JavaScript since it allows to pass any number of parameters of any type. You have to check inside the function how many arguments have been passed and what type they are.
Unlike the other programming languages, JavaScript Does not support Function Overloading.
TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.
You can just declare your pass
function as being of the type of the original
function using the typeof operator, e.g.
function original (a: number): boolean;
function original (a: string, b: string): boolean;
function original (): boolean {
return true;
}
let pass: typeof original = () => {
return true;
};
pass(5); // all good
pass('a', 'b'); // all godd
pass(45, 'b'); // error here
Playground here
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