Overloading a function in Typescript

You can overload a function as follows:
First you create the function with all it’s possible types using unions:

function combine (a: string | number, b: string | number): string | number {
  if (typeof a === 'string' || typeof b === 'string') {
    return a.toString() + b.toString();
  } else {
  return a + b;
  }
}

The downside of this, that you would need to cast the result of function to either a number or a string:

To overcome this we add more specific overloads:

function combine (a: string, b: string): string;
function combine (a: number, b: number): number;
function combine (a: string | number, b: string | number): string | number {
  if (typeof a === 'string' || typeof b === 'string') {
    return a.toString() + b.toString();
  } else {
  return a + b;
  }
}

And with these overloads, Typescript is smart enough to know what was returned: