TypeScript's Approach to Structural Typing: If It Walks and Quacks Like a Duck
Understanding prototypes in JavaScript has greatly enhanced my comprehension of the language and empowered me to utilize its full potential. I believe that Structural Typing, or Duck Typing, is a foundational concept that combines the strengths of JavaScript and is essential for a deeper understanding of TypeScript.
This concept is important because TypeScript is a statically typed superset of JavaScript. While the latter allows the usage of any type of data in any situation, the former restricts this to prevent potential type-related bugs. TypeScript ensures that the data used matches the expected structure, i.e., it has the correct "shape."
interface Duck {
walk: () => void;
quack: () => void;
}
function makeDuckMove(duck: Duck) {
duck.walk();
duck.quack();
}
const Unicorn = {
walk: () => console.log('Walking...'),
quack: () => console.log('Quacking...'),
jump: () => console.log('Jumping...')
};
makeDuckMove(Unicorn); // This is valid
In this example, the Duck interface describes a shape or structure of an object. If you can find a Unicorn that fulfills this structure (has a walk and quack method in this case) you can pass it into makeDuckMove function. The Unicorn object has more methods than the Duck interface requires. You may ask, doesn't this violate the share or structure of an object I mentioned earlier? As long the Unicorn meets the minimum requirement of the Duck interface, TypeScript won't complain. This is also known as duck typing or structural typing.
Repeat after me,
If it walks like a duck and quacks like a duck, TypeScript considers it a duck.
Edit: Fixed grammar in paragraph 2.