How to create function overload in TypeScript?


The function or method overloading allows developers to create multiple functions with the same name. Every function contains the same number of parameters but different data types. Also, the return type of the overloaded function can vary.

Function overloading is the concept of object-oriented programming. Also, TypeScript supports OOPS, so we can easily implement function overloading in TypeScript. Furthermore, function overloading provides code reusability and helps developers to increase code readability.

Let’s understand the use of function overloading via real-life examples. For example, you have created a function that takes a string as a parameter and returns the length of the string. Suppose we wanted to pass a number as a parameter; then, we need to overload the function by declaring a new function with the same name and taking the number as a parameter.

Syntax

Users can follow the syntax below to overload the function.

function function1(param1: string): number;
function function1(param1: number): number;
function function1(param1: any): any {
   // function body
}

In the above syntax, we have overloaded the fuction1. Users can observe that it takes the param of the string type in the first declaration and the param of the number type in the second declaration.

After that, we need to use any type for the parameter and return type while defining the function to support the number and string of both types.

Example

In the example below, the getStrLen() function is overloaded via the parameter type. The getStrLen() function can take either string or a number as a parameter and returns the number value representing the length of the string.

Users can see how we used the toString() method to convert number values to the string and get its length via the length property.

function getStrLen(str: string): number;
function getStrLen(str: number): number;
function getStrLen(str: any): any {
   // if the parameter is the number type, convert it to the string.
   if (typeof str != "string") {
      str = str.toString();
   }
   let length = str.length;
   return length;
}
// calling the functions with string and number parameters.
console.log("The string length is " + getStrLen("TutorialsPoint     "));
console.log("The length of number is " + getStrLen(10));

On compiling, it will generate the following JavaScript code −

function getStrLen(str) {
   // if the parameter is the number type, convert it to the string.
   if (typeof str != "string") {
      str = str.toString();
   }
   var length = str.length;
   return length;
}

// calling the functions with string and number parameters.
console.log("The string length is " + getStrLen("TutorialsPoint     "));
console.log("The length of number is " + getStrLen(10));

Output

The above code will produce the following output −

The string length is 19
The length of number is 2

Example

In this example, we compare the values passed as a parameter using the strict equality operator. Users can see that compareValues() function either takes three number values or string values.

After that, we return the Boolean value based on the result of the comparison of all three parameter values.

function compareValues(value1: number, value2: number, value3: number): boolean;
function compareValues(value1: string, value2: string, value3: string): boolean;
function compareValues(value1: any, value2: any, value3: any): any {
   if (value1 === value2 && value2 === value3) {
      return true;
   }
   return false;
}
console.log("Are 10, 20, and 30 same? " + compareValues(10, 20, 30));
console.log("Are 10, 10, and 10 same? " + compareValues(10, 10, 10));
console.log(
   "Are all three strings same? " +
   compareValues("TypeScript", "TypeScript", "TypeScript")
);

On compiling, it will generate the following JavaScript code −

function compareValues(value1, value2, value3) {
   if (value1 === value2 && value2 === value3) {
      return true;
   }
   return false;
}
console.log("Are 10, 20, and 30 same? " + compareValues(10, 20, 30));
console.log("Are 10, 10, and 10 same? " + compareValues(10, 10, 10));
console.log("Are all three strings same? " + compareValues("TypeScript", "TypeScript", "TypeScript"));

Output

The above code will produce the following output −

is 10, 20, and 30 are same? false
Are 10, 10, and 10 same? true
Are all three strings same? true

Example

The below example demonstrates to overload of the constructor function. We have created the class named data containing the three properties of different data types.

We have declared an empty constructor function with some parameters. While defining the constructor function, we have used the ‘?’ to make all parameters optional. After that, we have initialized the class properties with parameter values in the constructor function.

class data {
   public prop1: string | undefined;
   public prop2: number | undefined;
   public prop3: boolean | undefined;

   constructor();
   constructor(prop1: string, prop2: number, prop3: boolean);
   constructor(prop1?: string, prop2?: number, prop3?: boolean) {
      this.prop1 = prop1;
      this.prop2 = prop2;
      this.prop3 = prop3;
   }

   getValues(): void {
      console.log("The value of prop1 is " + this.prop1);
      console.log("The value of prop2 is " + this.prop2);
      console.log("The value of prop3 is " + this.prop3);
   }
}

let object = new data("Hi There!", 87, false);
object.getValues();

// creating the object without passing the constructor arguments.
let object1 = new data();
object1.getValues();

On compiling, it will generate the following JavaScript code −

var data = /** @class */ (function () {
   function data(prop1, prop2, prop3) {
      this.prop1 = prop1;
      this.prop2 = prop2;
      this.prop3 = prop3;
   }
   data.prototype.getValues = function () {
      console.log("The value of prop1 is " + this.prop1);
      console.log("The value of prop2 is " + this.prop2);
      console.log("The value of prop3 is " + this.prop3);
   };
   return data;
}());
var object = new data("Hi There!", 87, false);
object.getValues();

// creating the object without passing the constructor arguments.
var object1 = new data();
object1.getValues();

Output

The above code will produce the following output −

The value of prop1 is Hi There!
The value of prop2 is 87
The value of prop3 is false
The value of prop1 is undefined
The value of prop2 is undefined
The value of prop3 is undefined

In the above output, users can observe that all parameter values for object1 are undefined as we haven’t passed any argument to the constructor while creating the object.

Example

In this example, we will learn to overload the class methods. We have created the methods class containing the overloadMethod() method.

The overloadmethod() takes the string or Boolean value as a parameter. We have created the object of the class and invoked the overloadMethod() by taking the object as a reference and passing different parameter values.

class methods {
   public variable1: number = 543;
   overloadMethod(key1: string): void;
   overloadMethod(key1: boolean): void;
   overloadMethod(key1: any): any {
      console.log("The value of key1 is " + key1);
   }
}
let methodObj = new methods();
methodObj.overloadMethod("TypeScript");
methodObj.overloadMethod(false);

On compiling, it will generate the following JavaScript code −

var methods = /** @class */ (function () {

   function methods() {
      this.variable1 = 543;
   }
   methods.prototype.overloadMethod = function (key1) {
      console.log("The value of key1 is " + key1);
   };
   return methods;
}());
var methodObj = new methods();
methodObj.overloadMethod("TypeScript");
methodObj.overloadMethod(false);

Output

The above code will produce the following output −

The value of key1 is TypeScript
The value of key1 is false

In this tutorial, users learned the concept of function overloading via different examples. Users can overload the function via parameters or return the type of the function. Also, we learned to overload the constructor function and class methods.

Updated on: 20-Jan-2023

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements