Duck Typing TypeScript
Duck-Typing is a method/rule used by TypeScript to check type compatibility for more complex variable types. This method is used to compare two objects by determining whether they have the same type of matching names or not. It means we can't change a variable's signature.
Assume we assign an object with two attributes, such as name and address, and the following time we set an object with more or fewer properties, or both properties are not set (name, address). The TypeScript compiler will output a compile-time error in that situation. Duck typing is the name for this notion.
In TypeScript programming, the duck-typing feature ensures type safety. The TypeScript compiler uses the duck-typing rule to determine whether an object is identical.
Also see, Types of information system
Example
The following example illustrates the duck typing in TypeScript:
class Dog {
sound = "barking";
}
class Lion {
sound = "roaring";
}
class Goat {
sound = "bleat";
swim(){
console.log("Cannot Swim!");
}
}
let lion: Lion = new Dog(); // substitutes
let dog: Dog = new Lion(); // substitutes
let lionTwo: Lion = new Goat();
//let goat: Goat = new Lion(); // IDE & compiler error
console.log("Lion Sound: "+lion.sound);
console.log("Dog sound: "+dog.sound);
console.log("Lion sound: "+lionTwo.sound);
Because the Goat class includes an additional function, it is impossible to substitute a Lion for a Goat in the example above (so Lion fails duck typing). In duck typing, dog and lion are interchangeable because a lion can't accomplish anything that a dog can't, and vice versa.