Function Overloading

With function overloading you can define multiple functions with the same name but with different input and output types.

It is a useful technique when there are a limited number of possible input types for a function and the return type depends on the input type. When calling an overloaded function, the TypeScript compiler will look for the function signature that best matches the input parameters and return the corresponding type. This saves the users of your function from having to specify the type argument and improves the Developer Experience (DX).

Example:

1
2
3
4
5
6
7
8
9
10
11
// Function Overload #1
function combine(x: number, y: number): number[];
// Function Overload #2
function combine(x: string, y: string): string[];
// Function Implementation
function combine(x: number | string, y: number | string) {
return [x, y];
}

combine('1', '2'); // string[] will be returned
combine(1, 2); // number[] will be returned

Video Tutorial:

Generics vs. Function Overloading

When the possible types are many and you don’t know exactly what type your users put in, then Generis are better suited. Generics allow you to specify the type argument which can make it easier to work with functions that can handle a wide range of input types.