0
0
Typescriptprogramming~3 mins

Why What structural typing means in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could understand objects by their shape, not just their name?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
interface BoxA { handle: string; weight: number; }
interface BoxB { label: string; weight: number; }
function liftBox(box: BoxA) { /* only boxes with handle property allowed */ }
After
interface HasHandle { handle: string; }
function liftBox(box: HasHandle) { /* any box with handle property allowed */ }
What It Enables

It allows flexible and safe code that works with any object having the right shape, making your programs easier to write and maintain.

Real Life Example

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.

Key Takeaways

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.