Nested Conditional Types
What You'll Learn
You'll learn how to chain multiple conditional types together to create sophisticated branching logic that handles complex type-level decisions.
What Are Nested Conditional Types?
Just like you can nest if-else statements in JavaScript to handle complex decision trees, you can nest conditional types in TypeScript to express multi-level type logic.
A nested conditional type is simply a conditional type where the true or false branch (or both) contains another conditional type. This lets you check multiple conditions in sequence, creating powerful type transformations.
The Pattern
The basic structure looks like this:
type ComplexCheck<T> =
T extends FirstCondition ? ResultA :
T extends SecondCondition ? ResultB :
T extends ThirdCondition ? ResultC :
DefaultResult;
Each branch can evaluate to another conditional, creating a cascade of checks similar to a multi-way if-else if-else chain.
Example: Deeply Unwrapping Types
type DeepUnwrap<T> =
T extends Promise<infer U> ? DeepUnwrap<U> :
T extends Array<infer V> ? DeepUnwrap<V> :
T;
type Test1 = DeepUnwrap<Promise<Promise<string>>>; // string
type Test2 = DeepUnwrap<Array<Array<number>>>; // number
type Test3 = DeepUnwrap<Promise<Array<boolean>>>; // boolean
Here, we recursively unwrap both Promises and Arrays until we reach a primitive type.
Think of It Like Peeling an Onion
Each layer of nesting checks one condition and decides whether to peel another layer or return the final type. This is particularly useful when dealing with wrapped types, normalized structures, or multi-step type transformations.
Key Takeaway: Nested conditional types allow you to chain multiple type checks together, creating complex branching logic that can recursively transform types through multiple levels of conditions.