Discover how union and intersection types can clear up your confusion and make your code smarter!
Union vs intersection mental model in Typescript - When to Use Which
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.
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.
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.
function handle(item: Pen | Marker) { if (item.type === 'pen') { /* pen logic */ } else if (item.type === 'marker') { /* marker logic */ } }type PenMarker = Pen & Marker; // item must be both pen and markerYou can precisely describe and work with complex data shapes, making your programs smarter and less error-prone.
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.
Union types let you accept one type or another.
Intersection types require all combined types together.
They help organize and clarify your code logic.