Duck Typing is a common method for type safety checks in dynamically typed languages. Its name originates from the phrase 'If it walks like a duck and quacks like a duck, then it probably is a duck.' In statically typed languages like TypeScript, Duck Typing manifests as structural subtyping (Structural Subtyping) or is referred to as a structural type system.
In TypeScript, if two objects share the same structure, TypeScript treats them as equivalent types. This means type compatibility is determined by the members of the objects, differing from traditional nominal type systems that require explicit declarations to establish compatibility.
Examples:
Consider the following TypeScript code:
typescriptinterface Duck { walk: () => void; quack: () => void; } function makeTheAnimalQuack(duck: Duck) { duck.quack(); } const myDuck = { walk: () => console.log("The duck is walking."), quack: () => console.log("The duck quacks."), swim: () => console.log("The duck swims.") }; // Although `myDuck` is not explicitly declared as the `Duck` type, it possesses the `walk` and `quack` methods, matching the structure defined by the `Duck` interface. Thus, the TypeScript compiler recognizes `myDuck` as conforming to the `Duck` type, enabling it to be passed to `makeTheAnimalQuack`. makeTheAnimalQuack(myDuck);
In this example, the myDuck object is not explicitly declared to implement the Duck interface, but it has the walk and quack methods that align with the structure of the Duck interface. Consequently, the TypeScript compiler deems myDuck compatible with the Duck type, allowing it to be passed as an argument to makeTheAnimalQuack.
This type-checking approach enhances TypeScript's flexibility and expressiveness, enabling developers to write more generic and reusable code without compromising type safety.