Conditional Types with Generic Constraints
What you'll learn: How to combine conditional types with generic constraints to narrow your input type before evaluating branches, making your type transformations safer and more precise.
The Core Idea
You've learned conditional types (T extends U ? X : Y) and generic constraints (<T extends Something>). Now we combine them: add a constraint to the generic parameter first, then use a conditional inside.
This pattern lets you:
- Guarantee the input meets minimum requirements (via constraint)
- Refine further based on specific characteristics (via conditional)
Think of it like airport security with two checkpoints: the constraint is the outer gate ("you must have a ticket"), and the conditional is the inner scanner ("now let's see if you're domestic or international").
Basic Pattern
type OnlyStringValues<T extends object> = {
[K in keyof T]: T[K] extends string ? T[K] : never;
};
// T must be an object (constraint)
// Then we check if each value is a string (conditional)
The extends object constraint prevents passing primitives, while the conditional type filters properties afterward.
Why This Matters
Without the constraint, you'd get confusing errors or unsafe behavior:
// Unsafe: no constraint
type Unsafe<T> = T extends string ? Uppercase<T> : never;
// Safe: constraint first
type Safe<T extends string> = T extends `get${infer Rest}`
? Rest
: never;
The constraint narrows the universe of possible inputs before the conditional even runs, preventing type errors deep in your logic.
Key Takeaway: Use <T extends Constraint> to establish minimum requirements, then apply conditional types within that narrowed space for safer, more predictable type transformations.