Concept Flow - Nested conditional types
Start with Type T
Check Condition 1: T extends X?
Check Condition 2: T extends Y?
Return Type A
The type checks T against conditions step-by-step, returning different types based on nested checks.
type Nested<T> = T extends string ? T extends "hello" ? "Greeting" : "String" : "Other"; // Example: Nested<'hello'>
| Step | Type T | Condition | Result | Returned Type |
|---|---|---|---|---|
| 1 | "hello" | T extends string? | true | Check next condition |
| 2 | "hello" | T extends "hello"? | true | "Greeting" |
| 3 | "world" | T extends string? | true | Check next condition |
| 4 | "world" | T extends "hello"? | false | "String" |
| 5 | 42 | T extends string? | false | "Other" |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | Final |
|---|---|---|---|---|---|---|
| T | generic | "hello" | "hello" | "world" | "world" | 42 |
| Condition 1 (T extends string) | unknown | true | true | true | true | false |
| Condition 2 (T extends "hello") | unknown | true | true | false | false | n/a |
| Returned Type | none | check next | "Greeting" | check next | "String" | "Other" |
Nested conditional types syntax: type Result<T> = T extends X ? (T extends Y ? A : B) : C; Checks conditions inside conditions. Returns type A if T matches Y inside X. Returns B if T matches X but not Y. Returns C if T does not match X.