0
0
Typescriptprogramming~3 mins

Union vs intersection mental model in Typescript - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how union and intersection types can clear up your confusion and make your code smarter!

The Scenario

Imagine you have a box of different colored pens and a box of different colored markers. You want to pick items that are either pens or markers, or sometimes only those that are both pens and markers. Doing this by sorting each item manually is confusing and slow.

The Problem

Manually checking each item to see if it belongs to one group or both is tiring and easy to mess up. You might forget some items or mix categories, leading to mistakes and wasted time.

The Solution

Using union and intersection types in TypeScript helps you clearly define whether you want items that belong to one group or both. This makes your code simpler, safer, and easier to understand.

Before vs After
Before
function handle(item: Pen | Marker) { if (item.type === 'pen') { /* pen logic */ } else if (item.type === 'marker') { /* marker logic */ } }
After
type PenMarker = Pen & Marker; // item must be both pen and marker
What It Enables

You can precisely describe and work with complex data shapes, making your programs smarter and less error-prone.

Real Life Example

Think of a user profile that can be a 'Guest' or 'Member' (union), but sometimes you need a user who is both a 'Member' and an 'Admin' (intersection) to allow special access.

Key Takeaways

Union types let you accept one type or another.

Intersection types require all combined types together.

They help organize and clarify your code logic.