Easy learning with example program codes

typescript duck typing tutorial

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.


class Sparrow {
    sound = "cheep";
class Parrot {
    sound = "squawk";
class Duck {
    sound = "quack";
        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);

Try it:

JS Bin on

TypeScript Tutorial

TypeScript Overview.
Typescript vs Javascript.
Typescript let vs var.
TypeScript Hello World.
Typescript Data Types.
Typescript Variable Declaration.
TypeScript operators list.
TypeScript Arithmetic Operators.
TypeScript Comparison Operators.
TypeScript Bitwise Operators.
Typescript Logical Operators.
TypeScript Assignment Operators.
Typescript Conditional Operator.
Typescript String Operator.
Typescript typeof Operator.
TypeScript control statements.
TypeScript Switch Statement.
TypeScript for loop.
TypeScript for in loop.
TypeScript while loop.
TypeScript do while loop.
Typescript for loop break.
TypeScript for loop continue.
Typescript function.
Typescript returning function.
Typescript parameterized function.
Typescript function optional parameter.
Typescript rest parameters.
Typescript default parameters.
Typescript anonymous function.
Typescript function constructor.
Typescript Arrow/Lambda function.
Typescript function overloading.
TypeScript number object.
TypeScript string object.
TypeScript boolean object.
TypeScript date object.
TypeScript math object.
TypeScript array object.
TypeScript tuples.
TypeScript union type.
TypeScript interface.
TypeScript interface inheritance.
TypeScript interface multiple inheritance.
TypeScript class.
Typescript class inheritance.
Typescript class interface.
TypeScript abstract class.
TypeScript object.
TypeScript duck typing.
TypeScript NameSpace.
TypeScript Multi-file namespaces.
TypeScript module.
TypeScript ambient module.

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki