When Unions Are Better: Known Fixed Options
You'll learn: When to prefer union types over generics for representing a fixed set of concrete possibilities.
The Right Tool for Known Options
When you have a fixed, predetermined set of concrete values that won't change based on some external type parameter, union types are the clear winner over generics.
Think of it like a restaurant menu: if you offer exactly three sizes—"small", "medium", and "large"—you don't need a generic Size<T> type. You have a known, closed set of options that should be explicitly listed.
Why Unions Win Here
Unions excel when:
- The options are known at authoring time — You can list every valid value
- The set is closed — New values aren't derived from type parameters
- Autocomplete matters — Users should see exactly what's allowed
- Type safety is local — The constraint doesn't propagate through generic flows
// ✅ Perfect use of union: fixed status options
type OrderStatus = "pending" | "shipped" | "delivered" | "cancelled";
function updateOrder(id: string, status: OrderStatus) {
// Autocomplete shows all four options
// Type checker prevents typos
}
// ❌ Overkill with generics for this case
type GenericStatus<T extends string> = T;
function updateOrderGeneric<T extends string>(id: string, status: T) {
// Loses the fixed set constraint
// Any string is now valid
}
The union version provides exact autocomplete, catches typos immediately, and clearly documents the valid options. Generics would add complexity without benefit since we're not preserving or transforming a type—we're selecting from a known list.
Key Takeaway: Use union types when you have a fixed, known set of concrete options at authoring time—they provide better autocomplete, clearer intent, and simpler types than generic alternatives.