Advertisement
Beginner TypeScript, Structural Typing & Duck Typing

What does 'structural typing' mean, and how does it differ from the 'nominal typing' used in languages like Java or C#?

Short answer

Structural typing determines type compatibility based purely on the SHAPE of a type — what properties/methods it has — rather than its declared NAME or explicit inheritance relationship (nominal typing).

Save TypeScript mock interview
Advertisement
AModel answer
Structural typing determines type compatibility based purely on the SHAPE of a type — what properties/methods it has — rather than its declared NAME or explicit inheritance relationship (nominal typing). If two unrelated types happen to have the same shape, TypeScript treats them as compatible, unlike Java/C# which require an explicit class/interface relationship.
interface Point { x: number; y: number; }
class Vector { constructor(public x: number, public y: number) {} }
function printPoint(p: Point) { console.log(p.x, p.y); }
printPoint(new Vector(1, 2)); // works! Vector has the same SHAPE as Point, despite no declared relationship
Real-world example
Passing a plain object literal or an instance of an unrelated class anywhere an interface is expected, as long as the shape matches.
Likely follow-ups
  • What's the common phrase used to describe this kind of shape-based compatibility, borrowed from Python?
Related topics