Q2: What is Structural Typing (Duck Typing) and how does it differ from Nominal Typing?
TypeScript uses a Structural Type System. Types are evaluated solely by their shape or structure (the properties and methods they possess), rather than their explicit declaration name or inheritance chain.
In Nominal Type Systems (like Java or C#), two objects with identical properties are not interchangeable unless they explicitly inherit from the same named class or interface.
Structural Compatibility Example
interface Point2D { x: number; y: number; }
interface Vector2D { x: number; y: number; }
const logPoint = (p: Point2D) => console.log(`${p.x}, ${p.y}`);
const velocity: Vector2D = { x: 10, y: 20 };
logPoint(velocity); // Valid! Vector2D matches the structure of Point2D.💡 Even though velocity is typed as Vector2D, TypeScript accepts it because its internal structure matches Point2D.
Key Takeaways
- TypeScript checks structure, not explicit declaration names.
- If an object has the required fields with matching types, TypeScript considers it compatible.