In TypeScript, function overloading is achieved by declaring multiple function signatures with different types and/or numbers of arguments, but with a single implementation.
The main characteristic: there is always one implementation, and the compiler checks if the call matches one of the declared signatures.
function greet(person: string): string; function greet(person: string, age: number): string; function greet(person: string, age?: number): string { if (age !== undefined) { return `Hello, ${person}. You are ${age}!`; } else { return `Hello, ${person}!`; } } greet('Alice'); // 'Hello, Alice!' greet('Bob', 32); // 'Hello, Bob. You are 32!'
⚠️ Unlike C# or Java, there are no multiple implementations of the function — all signatures resolve to one function with mandatory checks inside.
Do you need to implement each overloaded signature in TypeScript as a separate function, as in C#?
Answer: No! In TypeScript, there is only one implementation for an overloaded function. All variations are specified through a set of signature declarations. It is the implementation that must handle various input parameter scenarios within one function.
Story
On a project, a developer declared two functions with the same name, hoping for overloading, as in Java. In the end, only the last defined function worked, while the others were "overwritten". This led to unexpected errors in operation and huge time costs for refactoring.
Story
They did not implement proper type checking within the implementation of the overloaded function. The function periodically returned values of the wrong type that clients expected, which caused difficulties in error catching since TypeScript does not validate overload implementations.
Story
They used an overload implementation only at the type level (declared signatures), but did not ensure compatibility with the runtime implementation (absence of optional parameters and checks within the function). This led to crashes when called with "valid by type" parameters, because the runtime did not support these options.