TypeScript Duck Typing

As defined by TypeScript, Duck-Typing is a technique used to evaluate type compatibility for more intricate variable types.

TypeScript employs the duck-typing approach to evaluate objects against one another by verifying whether they share matching type names. This implies that the signature of a variable cannot be altered. For instance, if an object is assigned with two properties, such as name and address, and subsequently, an object with either additional properties, fewer properties, or properties that differ from (name, address) is assigned, the TypeScript compiler will raise a compile-time error. This principle is referred to as Duck typing.

The duck-typing capability ensures type safety within TypeScript code.

The TypeScript compiler utilizes the principle of duck typing to determine whether one object is equivalent to another.

In accordance with the duck-typing approach, it is essential for both objects to possess identical types of properties or variables.

Example

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);

output

In the preceding example, it is evident that replacing a Goat with a Lion is not permitted since the Goat class possesses an extra method (therefore, Lion does not meet the criteria for duck typing). However, Dog and Lion can be interchanged in the context of duck typing because there are no actions that a Lion can perform that a Dog cannot replicate, and the same holds true in reverse.

Input Required

This code uses input(). Please provide values below: