EN
TypeScript - class methods overloading
7 points
In this article, we would like to show how to overload method in class in u>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 inside class.
Quick solution:
xxxxxxxxxx
1
class SomeClass {
2
3
public someMethod(): ResultType; // <----- declaration
4
public someMethod(a: ArgType1): ResultType; // <----- declaration
5
public someMethod(a: ArgType2, b: ArgType3): ResultType; // <----- declaration
6
// ...
7
8
public someMethod(a?: any, b?: any): ResultType { // <----- definition
9
// ... // <----- definition
10
} // <----- definition
11
}
12
13
// ...
xxxxxxxxxx
1
class Printer {
2
3
public print(a: string): void; // <----- declaration
4
public print(a: string, b: string): void; // <----- declaration
5
6
public print(a: string, b?: string): void { // <----- definition
7
if (b) { // <----- definition
8
console.log(a + ' ' + b); // <----- definition
9
} else { // <----- definition
10
console.log(a); // <----- definition
11
} // <----- definition
12
} // <----- definition
13
}
14
15
const printer = new Printer();
16
17
printer.print('Hi!');
18
printer.print('Hi', 'John!');
Output:
xxxxxxxxxx
1
Hi!
2
Hi John!