When You Need Both: Generic Constrained by Union
You'll learn: How to combine the flexibility of generics with the safety of union constraints using the pattern T extends 'a' | 'b' | 'c'.
The Pattern That Combines Both Worlds
Sometimes you face a design problem where unions alone are too rigid (they widen away the specific type), but unconstrained generics are too loose (they allow anything). The solution is a generic type parameter constrained by a union: T extends 'a' | 'b' | 'c'.
This pattern means: "T can be any specific type, but only if it's one of these known options."
Why You Need This
Imagine you're building a configuration system where you have known status types, but you want functions to remember the exact status passed in:
type Status = 'idle' | 'loading' | 'success' | 'error';
// Without generic - loses precision
function createMessage(status: Status): string {
return `Status is ${status}`;
}
const msg = createMessage('loading'); // msg is just string
// With constrained generic - preserves precision
function createTypedMessage<T extends Status>(status: T): `Status is ${T}` {
return `Status is ${status}`;
}
const typedMsg = createTypedMessage('loading');
// typedMsg is "Status is loading" - exact literal type!
The generic T preserves the specific literal type, while extends Status ensures only valid status values are accepted.
Real-World Application
This pattern shines in event systems, routing, state machines, and configuration builders where you have a finite set of known values but need to preserve which specific value was used:
type EventType = 'click' | 'hover' | 'focus';
function createHandler<T extends EventType>(
eventType: T,
handler: (type: T) => void
): { type: T; handler: (type: T) => void } {
return { type: eventType, handler };
}
const clickHandler = createHandler('click', (type) => {
// type is exactly 'click', not EventType union
console.log(type);
});
Key Takeaway: Use T extends 'a' | 'b' | 'c' when you need generic type preservation with union-based validation—it gives you type safety boundaries with specific type memory.