Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have functions pass arguments with the same overloads?

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

like image 635
ThomasReggi Avatar asked Dec 02 '20 15:12

ThomasReggi


People also ask

What are the restrictions on overloaded functions?

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.

Why JavaScript does not support method overloading?

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.

Is function overloading possible in JavaScript?

Unlike the other programming languages, JavaScript Does not support Function Overloading.

Is there function overloading in TypeScript?

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.


1 Answers

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

like image 184
dezfowler Avatar answered Nov 15 '22 10:11

dezfowler