What is 'duck typing' and how does the phrase 'if it walks like a duck and quacks like a duck' apply to TypeScript?
Short answer
Duck typing (the phrase's origin) means a value's suitability is judged by whether it HAS the behavior/shape you need, not by what it's formally declared to be — TypeScript's structural type system directly embodies this: any value with the right shape is accepted, regardless of…
Advertisement
AModel answer
Duck typing (the phrase's origin) means a value's suitability is judged by whether it HAS the behavior/shape you need, not by what it's formally declared to be — TypeScript's structural type system directly embodies this: any value with the right shape is accepted, regardless of its declared type name or class hierarchy.
interface Quacks { quack(): void; }
function makeItQuack(thing: Quacks) { thing.quack(); }
makeItQuack({ quack: () => console.log('Quack!') }); // works -- has the right shape, no formal 'Duck' type neededReal-world example
Accepting any object with the right method/property shape as a valid argument, without requiring it to formally implement an interface.
Likely follow-ups
- Does this mean you never actually NEED to use 'implements' in TypeScript for structural compatibility to work?
Related topics