TypeScript
/Beginner
Union Types
Definition
A Union Type is a type formed from two or more other types, representing values that may be any one of those types. It uses the pipe `|` symbol.
Explain Like I'm New
A Union type is an 'OR' operator for types. It tells TypeScript: 'This variable is allowed to be a String OR a Number. Either one is completely fine.'
Real World Example
A function that finds a user by ID. Sometimes the ID is from a URL (so it's a string '123'), sometimes it's from a database (so it's a number 123). You type the parameter as `id: string | number`.
Common Use Cases
- •Handling diverse inputs
- •API responses that return different shapes based on status
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What symbol is used for Union Types?
intermediate
- If a parameter is `string | number`, can you call `.toUpperCase()` on it immediately?
advanced
- What is Type Narrowing?