Polymorphism in JavaScript

There are two approaches by which we can use Polymorphism in JavaScript. One by checking the argument types or by another approach by tracking an object at the last argument of a function.

Polymorphism by Checking Argument Type
 function CatStrings(p1, p2, p3)
 {
   var s = p1;
   if(typeof p2 !== "undefined") {s += p2;}
   if(typeof p3 !== "undefined") {s += p3;}
   return s;
 };

 CatStrings("one");        // result = one
 CatStrings("one",2);      // result = one2
 CatStrings("one",2,true); // result = one2true
Polymorphism by Tracking an object
 function foo(a, b, opts) {
 }

 foo(1, 2, {"method":"add"});
 foo(3, 4, {"test":"equals", "bar":"tree"});

Polymorphism in Typescript

However TypeScript end result is Plain JavaScript, we can only provide the single method block. Through the use of conditional statements;

class Car{
    setSpeed(message: string);
    setSpeed(message: number);
    setSpeed(message: boolean);
    setSpeed(message: any) {
        if (typeof message === "string") {
            alert(message);
        } else if (typeof message === "number") {
            alert("The number provided was: " + message);
        } else if (typeof message === "boolean") {
            alert("The boolean value was: " + message);
        } else {
            alert(message);
        }
    }
}

var car = new Car();
car.setSpeed(false);

results matching ""

    No results matching ""