Concept Flow - Conditional type syntax
Start with Type T
Check Condition: T extends U?
Yes No
Use Type X
Result Type
The conditional type checks if type T fits type U. If yes, it uses type X; if no, it uses type Y.
type IsString<T> = T extends string ? "Yes" : "No"; type Test1 = IsString<string>; type Test2 = IsString<number>;
| Step | Type T | Condition (T extends string?) | Result Type |
|---|---|---|---|
| 1 | string | Yes | "Yes" |
| 2 | number | No | "No" |
| Variable | Start | After 1 | After 2 | Final |
|---|---|---|---|---|
| T | generic | string | number | number |
| Result Type | unknown | "Yes" | "No" | "No" |
Conditional types syntax: type Result = T extends U ? X : Y; Checks if T fits U. If yes, Result is X. If no, Result is Y. Used for type decisions at compile time.
T extends U ? X : YT extends U ? X : Y means if type T can be assigned to type U, then use type X.type Result = T extends U ? X : Y; to define conditional types.type Check<T> = T extends string ? number : boolean;
type Result = Check<'hello'>;
type Example<T> = T extends number ? 'num' : 'not num'
type Example<T> = T extends number ? 'num' : 'not num' is valid in TypeScript.type Flatten<T> = T extends any[] ? T[number] : T;
Flatten<string[] | number>?Pass the test and this pattern moves unknown