Languages
[Edit]
EN

TypeScript - class methods overloading

7 points
Created by:
Mariam-Barron
841

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!

 

See also

  1. TypeScript - function overloading

Alternative titles

  1. TypeScript - class method overloading
  2. TypeScript - class functions overloading
  3. TypeScript - class function overloading
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join