What is structural typing in TypeScript?

Answer

Structural typing (also called "duck typing" or "nominal-free typing") means TypeScript determines type compatibility based on the structure (shape) of a type — the properties and methods it has — rather than by explicit declarations or type names. If two types have the same structure, they are compatible, regardless of their names. Example: interface Cat { name: string; meow(): void; } class Dog { name: string = "Rex"; meow() {} } — a Dog instance is assignable to Cat because it has the same structure. This contrasts with nominal typing (used in Java/C#), where only explicitly declared types can be used in place of each other. Structural typing makes TypeScript very flexible and great for working with existing JavaScript patterns. However, it can cause surprises: two completely unrelated types can be compatible if their shapes align. For cases where you want nominal-like behavior (e.g., ensuring an ID from table A cannot be used for table B), use branded types.