What if your program could understand objects by their shape, not just their name?
Why What structural typing means in Typescript? - Purpose & Use Cases
Imagine you have many different boxes with various items inside, and you want to check if a box has a handle before lifting it. Without a clear way to check, you might have to open each box and guess if it has a handle.
Manually checking each box's contents is slow and confusing. You might miss a handle or mistake one box for another. This makes your work error-prone and frustrating.
Structural typing lets you check if a box has a handle by looking at its shape or features, not its label. If it has a handle property, you can lift it safely, no matter what the box is called.
interface BoxA { handle: string; weight: number; }
interface BoxB { label: string; weight: number; }
function liftBox(box: BoxA) { /* only boxes with handle property allowed */ }interface HasHandle { handle: string; }
function liftBox(box: HasHandle) { /* any box with handle property allowed */ }It allows flexible and safe code that works with any object having the right shape, making your programs easier to write and maintain.
When building a delivery app, you can accept any package object that has an address and weight, regardless of its exact type name, ensuring smooth handling of diverse packages.
Structural typing checks an object's shape, not its name.
This makes code more flexible and less error-prone.
You can use objects with the right features anywhere, no matter their declared type.