Search code examples
typescriptoverloading

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


Solution

  • 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 good
    pass(45, 'b');   // error here
    

    Playground here