Conditional Constraints with Nested Generics
What you'll learn: How to apply different restrictions to nested generic types based on the shape of their outer type.
When working with generics inside generics, you often need different constraints depending on what the outer generic type looks like. Conditional constraints let you say "if the outer type has this shape, then the inner type must follow these rules."
The Core Idea
Think of it like a set of nested boxes where the rules for the inner box depend on the type of outer box you have. A music box might require small, delicate items inside, while a toolbox accepts heavier objects. Similarly, your generic constraints can change based on what type parameter you're working with.
Syntax Pattern
You combine conditional types in the extends clause with nested generic type parameters:
type Helper<T, K extends T extends string ? number : boolean> = {
value: T;
meta: K;
};
// When T is string, K must be number
type A = Helper<string, 42>; // ✓ Valid
// When T is not string, K must be boolean
type B = Helper<number, true>; // ✓ Valid
type C = Helper<number, 42>; // ✗ Error: K must be boolean
Nested Generics with Shape-Based Constraints
type Container<
T,
V extends T extends Array<any> ? T[number] : never
> = {
data: T;
processor: (item: V) => void;
};
// V must match array element type
type NumberList = Container<number[], number>;
The inner generic V is constrained conditionally: if T is an array, V must match its element type.
Key Takeaway: Conditional constraints with nested generics let you enforce different type restrictions for inner type parameters based on the shape or properties of outer type parameters, creating more flexible yet type-safe generic utilities.