Categories
TypeScript Answers

How to do method overloading in TypeScript?

Spread the love

Sometimes, we want to do method overloading in TypeScript.

In this article, we’ll look at how to do method overloading in TypeScript.

How to do method overloading in TypeScript?

To do method overloading in TypeScript, we can add multiple signatures for the same function.

For instance, we write

class C {
  someMethod(stringParameter: string): void;
  someMethod(numberParameter: number, stringParameter: string): void;
  someMethod(stringOrNumberParameter: any, stringParameter?: string): void {
    if (typeof stringOrNumberParameter === "number") {
      //...
    } else {
      //...
    }
  }
}

to add multiple signatures for the someMethod method in the C class.

The first parameter can be a number or a string according to the signatures.

And the 2nd parameter is optional.

Then in someMethod, we check if stringOrNumberParameter is a number with typeof.

Conclusion

To do method overloading in TypeScript, we can add multiple signatures for the same function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *