What if your program could understand things by their shape, not just their label?
How structural typing differs from nominal typing in Typescript - Why You Should Know This
Imagine you have two different boxes labeled 'Person' and 'Employee', each with the same contents inside. You want to check if you can use one box where the other is expected, but you have to open each box and compare every item manually.
This manual checking is slow and error-prone because you must remember every detail about the boxes' contents. If you miss something or mix up labels, your program might break or behave unexpectedly.
Structural typing lets the program automatically compare the contents of the boxes, ignoring their labels. If the contents match, it treats them as compatible, making your code more flexible and less error-prone.
interface Person { name: string; age: number; }
interface Employee { name: string; age: number; }
// Must manually check compatibilityinterface Person { name: string; age: number; }
interface Employee { name: string; age: number; }
// Structural typing allows automatic compatibilityThis concept enables seamless reuse of code by focusing on what data looks like, not what it's called.
When building a contact list app, you can use the same function to handle both 'Customer' and 'Supplier' objects as long as they have the same properties, without extra code to convert or check types.
Manual type checks are slow and risky.
Structural typing compares data shapes, not names.
This leads to more flexible and safer code.