EN
TypeScript - function overloading
8
points
In this article, we would like to show how to overload function in TypeScript.
TypeScript supports function overloading syntax that lets to deflate multiple functions with the same name, different arguments and return types. It is required just to provide some functions declarations and one function definition.
Note: go to this article to know how to overload method in class.
Quick solution:
function someMethod(): ResultType; // <----- declaration
function someMethod(a: ArgType1): ResultType; // <----- declaration
function someMethod(a: ArgType2, b: ArgType3): ResultType; // <----- declaration
// ...
function someMethod(a?: any, b?: any): ResultType { // <----- definition
// ... // <----- definition
} // <----- definition
// ...
Practical example
function print(a: string): void; // <----- declaration
function print(a: string, b: string): void; // <----- declaration
function print(a: string, b?: string): void { // <----- definition
if (b) { // <----- definition
console.log(a + ' ' + b); // <----- definition
} else { // <----- definition
console.log(a); // <----- definition
} // <----- definition
} // <----- definition
print('Hi!');
print('Hi', 'John!');
Output:
Hi!
Hi John!
Alternative solution
type Print = { // <----- declaration
(a: string): void; // <----- declaration
(a: string, b: string): void; // <----- declaration
}; // <----- declaration
const print: Print = (a: string, b?: string): void => { // <----- definition
if (b) { // <----- definition
console.log(a + ' ' + b); // <----- definition
} else { // <----- definition
console.log(a); // <----- definition
} // <----- definition
} // <----- definition
print('Hi!');
print('Hi', 'John!');