Javatpoint Logo
Javatpoint Logo

Function Overloading

In TypeScript, function overloading is a mechanism or ability which create multiple methods with the same name and with a different number of parameters or types. Function overloading is also known as method overloading.

Method overloading is allowed when -

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

Suppose we have to perform multiplication of the given numbers, but there can be a different number of parameters. If we write the method such as mul_a(number, number) for two parameters, and mul_b(number, number, number) for three parameters, then 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, function overloading is used which increases the readability of the program.

Advantage of function overloading

  • Function overloading or Method overloading increases the readability of the program.

Example

In the above example:

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

After compiling the above TypeScript code, the following JavaScript code will be generated.

Output:

Addition: Hello JavaTpoint
Addition: 50

Example of function overloading in a class:

After compiling the above TypeScript code, the following JavaScript code will be generated.

Output:

Result: 101
Length of String: 10

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

Example





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA