0
0
Typescriptprogramming~3 mins

How structural typing differs from nominal typing in Typescript - Why You Should Know This

Choose your learning style9 modes available
The Big Idea

What if your program could understand things by their shape, not just their label?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
interface Person { name: string; age: number; }
interface Employee { name: string; age: number; }
// Must manually check compatibility
After
interface Person { name: string; age: number; }
interface Employee { name: string; age: number; }
// Structural typing allows automatic compatibility
What It Enables

This concept enables seamless reuse of code by focusing on what data looks like, not what it's called.

Real Life Example

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.

Key Takeaways

Manual type checks are slow and risky.

Structural typing compares data shapes, not names.

This leads to more flexible and safer code.