Union Types and Narrowing
A union type means "one of these". Write it with |.
Real values are often one of several things: an id that's a number or a string, a payment that's UPI, card or cash. Union types describe this, and narrowing (checking the type) lets TypeScript know exactly which case you're in.
Example
Narrowing with typeof
With a union, TypeScript only lets you use what all the options share. Check the type first - this is called narrowing:
Example
Discriminated unions
Give each shape a common field like kind. A switch on it tells TypeScript exactly which shape you have:
Example
If you add a new payment kind later, TypeScript points to every switch that doesn't handle it yet. That is one of its biggest time-savers.
Key points
- A | B means A or B.
- Narrow with typeof, in, instanceof or a kind field.
- Discriminated unions make switches safe.
📝 Test yourself
1. What does number | string mean?
2. What is narrowing?
3. Fill in the operator that checks a primitive type:
if ( id === "number") { }
