TypeScript Union Types
🔀 TypeScript Union Types
They are written using the pipe symbol |.
📌 Think of union as OR → this OR that
1️⃣ Basic Union Type
2️⃣ Union Types with Functions
3️⃣ Union Types with Arrays
Array elements can be more than one type.
4️⃣ Union Types with Objects
5️⃣ Type Narrowing (Very Important ⭐)
TypeScript requires you to check the type before using it.
Using typeof
6️⃣ Union with Literal Types
Restrict values to exact options.
7️⃣ Union Types with null / undefined
Very common in real projects.
8️⃣ Discriminated Unions ⭐⭐
Use a common literal property to safely narrow types.
9️⃣ Union vs Intersection
| Feature | Union (|) | Intersection (&) |
|—-|—-|—-|
| Meaning | OR | AND |
| Values | One of many | Must satisfy all |
| Use Case | Flexible inputs | Combine features |
🔑 Union Types Summary
| Use Case | Example |
|---|---|
| Variable | string |
| Function Param | (a: number |
| Array | (number |
| Literal | “yes” |
| Null Safety | `string |
| Discriminated | kind: "type" |
⭐ Best Practices
✔ Always narrow union types
✔ Use discriminated unions for objects
✔ Prefer union types over any
✔ Combine with literal types for safety
