What Union Types Are
You'll learn: How TypeScript lets a single value represent multiple possible types using union types.
The Core Idea
A union type represents a value that could be one of several different types. You create a union type using the | (pipe) operator between type names.
Think of it like an "or" statement for types: "this value can be a string OR a number OR a boolean."
Why Union Types Matter
In JavaScript, variables often hold different types of values depending on context. Union types let you express this reality safely:
- A function parameter that accepts a string username or numeric user ID
- A variable that's either data or an error message
- A return value that could be successful data or null
The Basic Pattern
When you write:
string | number
You're declaring a type that accepts either a string or a number—but TypeScript still enforces that it must be one of those specific types. You can't assign a boolean, for example.
Example Without Code
Imagine a shipping label that accepts either a street address (text) or GPS coordinates (numbers). You wouldn't want to accidentally put a phone number there. A union type is like saying: "This field accepts format A or format B—nothing else."
TypeScript tracks which type you're working with and prevents you from mixing incompatible operations.
Key Takeaway: Union types let you declare that a value can be one of several specified types, written with the | operator, giving you type safety for JavaScript's dynamic patterns.