TypeScript uses structural typing, meaning that two types are considered compatible if they have the same properties, regardless of their name. In contrast, nominal typing checks type compatibility based on their names, even if they have the same properties.
Example of structural typing:
interface A { x: number; } interface B { x: number; } const a: A = { x: 10 }; const b: B = { x: 10 }; const c: A = b; // OK, because 'A' and 'B' have the same structure
In TypeScript, since it uses structural typing, objects A
and B
can be used interchangeably because they have the same structure. Nominal typing could restrict such an assignment.
The benefit of structural typing in TypeScript is greater flexibility and the ability to more easily combine types with similar structures, leading to less code and better interoperability in applications that need to merge different data structures.