Function Overloading in Typescript

Function Overloading in TypeScript

Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads, it is possible to statically describe the manner in which a function's return type varies based on its arguments. Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost.

The parameter list of a function overload cannot specify default values for parameters. In other words, an overload may use only the ? form when specifying optional parameters.

The following example shows the function overloading. In this example I make a Testclass and it has two functions with the same name but different signatures. Let's see how I implement overloading in TypeScript. Let's use the following.

Step 1

Open Visual Studio 2012 and click "File" -> "New" -> "Project...". A window is opened. In this window, click HTML Application for TypeScript under Visual C#. Give the name of your application as "overload" and then click ok.

Step 2

After this session the project has been created; a new window is opened on the right side. This window is called the Solution Explorer. The Solution Explorer contains the ts file, js file, css file and html file as in the following:




class TestClass {

    Method(x: string);

    Method(y: number, x: number):void;

    Method(y: any, x?: number):void


        if (y && typeof y == "number")


            var s: number;

        s = y * x;

        alert("First Overlode Function in Number ->" +s);         




        alert("Second Overlode Function in String ->" + y);




window.onload = () => {

    var obj1 = new TestClass();











    <title>Function Overloading Example</title>





    <h1>Function Overloading in TypeScript HTML App</h1>






var TestClass = (function () {

    function TestClass() { }

    TestClass.prototype.Method = function (y, x) {

        if(y && typeof y == "number") {

            var s;

            s = y * x;

            alert("First Overload Function in Number ->" + s);

        } else {

            alert("Second Overload Function in String ->" + y);



    return TestClass;


window.onload = function () {

    var obj1 = new TestClass();

    obj1.Method(5, 3);




Output 1


Click the "Ok" button.

Output 2



Reference By