Primitive Union Types
What you'll learn: How to use union types to allow a variable to hold one of several different primitive types.
What Is a Union Type?
A union type lets you say "this value can be Type A or Type B or Type C." It's like a multiple-choice option for your variable. Instead of locking into a single type like string or number, you can combine primitives using the pipe symbol (|) to represent values that might be different kinds.
Think of it like a parking spot that accepts either motorcycles or cars — not both at once, but either one is valid.
Syntax and Usage
let id: string | number;
id = "abc123"; // ✅ Valid: string is allowed
id = 42; // ✅ Valid: number is allowed
Here, id can hold either a string or a number. TypeScript tracks which type it currently is and won't let you assign something outside those options:
let status: "active" | "inactive" | "pending";
status = "active"; // ✅ Works
status = "completed"; // ❌ Error: not in the union
You can also combine null or undefined with other primitives:
let name: string | null = "Alice";
name = null; // ✅ Allowed
When to Use Union Types
Unions are perfect when a value legitimately has multiple valid forms — like a user ID that might be numeric or a string, or a configuration flag that's either true, false, or "auto".
Key Takeaway: Union types combine multiple primitive types with |, letting a variable hold one of several allowed types at any given time.