Literal Union
Problem
Functions accept any string or number when only specific values are valid, allowing typos and invalid values to pass compilation. Status fields accept “Pending” instead of “pending”, color properties accept “red” when only “primary” and “secondary” are supported, and theme values can be any string instead of the three defined themes. These bugs only surface at runtime when the values are used.
Solution
Restrict types to specific string or number values rather than accepting any value of that primitive type. This catches typos and invalid values at compile time.
Example
This example demonstrates how to use literal union types to restrict function parameters to specific string values, catching typos and invalid values at compile time.
// Define types that only accept specific string literals
type Status = 'pending' | 'approved' | 'rejected';
type Theme = 'light' | 'dark';
function setStatus(status: Status) {
// TypeScript ensures status is one of the allowed values
// Only 'pending', 'approved', or 'rejected' are accepted
}
// This call is valid - 'pending' matches the type
setStatus('pending'); // OK
// This call fails - 'Pending' is not in the union (case sensitive)
setStatus('Pending'); // Error
Benefits
- Catches typos and invalid values at compile time instead of runtime.
- Provides autocomplete for valid values in IDEs.
- Makes code self-documenting by encoding valid options in the type system.
- Prevents logic errors from using incorrect but syntactically valid values.
Tradeoffs
- Requires TypeScript or similar type system, not available in plain JavaScript.
- Can be restrictive if valid values need to be added dynamically.
- May need maintenance when valid options change over time.
- Doesn’t prevent runtime issues if data comes from external sources without validation.