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.
What does a nested conditional type in TypeScript allow you to do?
Example: type Example<T> = T extends string ? (T extends 'hello' ? number : boolean) : null;
T extends string. If yes, it checks again if T extends 'hello'.Which of the following is the correct syntax for a nested conditional type in TypeScript?
type Result<T> = T extends number ? (T extends 5 ? 'Five' : 'Other') : 'Not a number';
condition ? (nested condition ? trueType : falseType) : elseType.? and : operators. Options A, B, and D have syntax errors or invalid keywords.What is the resulting type of CheckType<"hello"> given this code?
type CheckType<T> = T extends string ? (T extends "hello" ? number : boolean) : null;
T is "hello", which extends string, so the outer condition is true.T extends "hello". It does, so the inner condition returns number.Identify the error in this nested conditional type:
type Test<T> = T extends number ? T extends 10 ? 'Ten' : 'Other' : 'Not a number'
T extends 10 ? 'Ten' : 'Other' must be wrapped in parentheses to group it properly.Given this nested conditional type, what is the type of Result<string | number>?
type Result<T> = T extends string ? (T extends 'a' ? 1 : 2) : (T extends number ? 3 : 4);
T = string | number, TypeScript applies the conditional to each union member separately.string: if 'a' then 1 else 2. For number: 3. So combined type is 1 | 2 | 3.Pass the test and this pattern moves unknown