Typescript duck typing

TypeScript duck typing:

Duck-typing is a powerful feature which brings strong typing concepts in TypeScript code. TypeScript provides the duck typing type-checking which focus on the shape that values have. It checks for the presence of certain properties in the objects instead of the actual object type.

The following example does not allow substitution of a Parrot for a Duck, because the Duck class has an additional method (so Parrot fails duck typing). Sparrows and Parrots are apparently substitutable in duck typing because there’s nothing a parrot can do that a sparrow cannot, and vice versa. Of course, a Duck can substitute for a Parrot, because if it sounds like a parrot, it is a parrot.

Example:

class Sparrow {
    sound = "cheep";
}
class Parrot {
    sound = "squawk";
}
class Duck {
    sound = "quack";
    swim(){
        console.log("Going for a dip!");
    }
}
var parrot: Parrot = new Sparrow(); // substitutes
var sparrow: Sparrow = new Parrot(); // substitutes
var parrotTwo: Parrot = new Duck();
//var duck: Duck = new Parrot(); // IDE & compiler error

console.log("Parrot says: "+parrot.sound);
console.log("sparrow says: "+sparrow.sound);
console.log("parrot says: "+parrotTwo.sound);


Please follow and like us:
Content Protection by DMCA.com