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:
xxxxxxxxxx
1
function someMethod(): ResultType; // <----- declaration
2
function someMethod(a: ArgType1): ResultType; // <----- declaration
3
function someMethod(a: ArgType2, b: ArgType3): ResultType; // <----- declaration
4
// ...
5
6
function someMethod(a?: any, b?: any): ResultType { // <----- definition
7
// ... // <----- definition
8
} // <----- definition
9
10
// ...
xxxxxxxxxx
1
function print(a: string): void; // <----- declaration
2
function print(a: string, b: string): void; // <----- declaration
3
4
function print(a: string, b?: string): void { // <----- definition
5
if (b) { // <----- definition
6
console.log(a + ' ' + b); // <----- definition
7
} else { // <----- definition
8
console.log(a); // <----- definition
9
} // <----- definition
10
} // <----- definition
11
12
print('Hi!');
13
print('Hi', 'John!');
Output:
xxxxxxxxxx
1
Hi!
2
Hi John!