Javatpoint Logo
Javatpoint Logo

TypeScript Function Overloading

Function overloading is a mechanism or ability to create multiple methods with the same name but different parameter types and return type. However, it can have the same number of parameters. Function overloading is also known as method overloading.

The Function/Method overloading is allowed when:

  • The function name is the same
  • The number of parameters is different in each overloaded function.
  • The number of parameters is the same, and their type is different.
  • The all overloads function must have the same return type.

Suppose we have to perform multiplication of the numbers, which has a different number of parameters. We write the two methods such as mul_a(number, number) for two parameters, and mul_b(number, number, number) for three parameters. Now, it may be difficult for us as well as other programmers to understand the behavior of the method because its name differs. In that case, we need to use function overloading, which increases the readability of the program.

Advantage of function overloading

  • It saves the memory space so that program execution becomes fast.
  • It provides code reusability, which saves time and efforts.
  • It increases the readability of the program.
  • Code maintenance is easy.

Example

In the above example:

  • The first two lines are the function overload declaration. It has two overloads:
    • A Function which accepts a string parameter.
    • A Function which accepts a number parameter.
  • The third line is the function definition, where the data type of the parameters is set to any.
  • The last two statements invoke the overloaded function.

After compiling the above TypeScript program, we will get the following JavaScript code.

Output:

TypeScript Function Overloading

Function overloading in a class

The following example helps to understand the use of method overloading in a class.

After compiling the above TypeScript program, we will get the following JavaScript code.

Output:

TypeScript Function Overloading

Function overloading with a different number of parameters and different types along with the same function name is not supported.

Example






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA