Combining Literal Types with Unions
What you'll learn: How to use union types with literal values to restrict variables and parameters to only an exact set of allowed values.
The Power of Literal Unions
You've learned how to create individual literal types (type One = 'one') and how to combine types with unions (string | number). Now we combine these two concepts to create incredibly precise types that only allow specific values.
By unioning literal types together, you create a type that acts like an enumeration—only certain values are valid:
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
let method: HttpMethod = 'GET'; // ✓ Valid
method = 'POST'; // ✓ Valid
method = 'PATCH'; // ✗ Error: not in the union
Why This Matters
Think of literal unions like a restaurant menu: you can order anything on the menu, but nothing else. TypeScript enforces this at compile time, preventing typos and invalid values.
This pattern is extremely common for:
type Direction = 'north' | 'south' | 'east' | 'west';
type Status = 'pending' | 'approved' | 'rejected';
type LogLevel = 'debug' | 'info' | 'warn' | 'error';
function setLogLevel(level: LogLevel) {
// TypeScript knows level can ONLY be those four strings
}
setLogLevel('info'); // ✓ Works
setLogLevel('verbose'); // ✗ Error
You can mix different literal types in the same union:
type Port = 80 | 443 | 8080; // Numeric literals
type Answer = true | false; // Boolean literals
type Mixed = 'auto' | 0 | false; // Mixed literals
Key Takeaway: Unioning literal types creates a precise, restricted set of allowed values, giving you compile-time safety for things like API methods, configuration options, and state values—far better than plain strings or numbers.