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:
class SomeClass {
public someMethod(): ResultType; // <----- declaration
public someMethod(a: ArgType1): ResultType; // <----- declaration
public someMethod(a: ArgType2, b: ArgType3): ResultType; // <----- declaration
// ...
public someMethod(a?: any, b?: any): ResultType { // <----- definition
// ... // <----- definition
} // <----- definition
}
// ...
Practical example
class Printer {
public print(a: string): void; // <----- declaration
public print(a: string, b: string): void; // <----- declaration
public print(a: string, b?: string): void { // <----- definition
if (b) { // <----- definition
console.log(a + ' ' + b); // <----- definition
} else { // <----- definition
console.log(a); // <----- definition
} // <----- definition
} // <----- definition
}
const printer = new Printer();
printer.print('Hi!');
printer.print('Hi', 'John!');
Output:
Hi!
Hi John!