Conditional types select one of two possible types based on a type relationship condition, expressed using a ternary-like syntax: T extends U ? X : Y.
flowchart TD
A["T extends U ? X : Y"] --> B{"Does T extend U?"}
B -- "Yes" --> C["Evaluates to Type X"]
B -- "No" --> D["Evaluates to Type Y"]
// Basic Conditional Type
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
// Extracting Return Type using infer keyword
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
type ResolvedNumber = UnpackPromise<Promise<number>>; // number
type UnchangedString = UnpackPromise<string>; // string
async function fetchScore(): Promise<number> {
return 98;
}
type FetchScoreReturn = UnpackPromise<ReturnType<typeof fetchScore>>; // number
console.log("Conditional types unpacked successfully.");
infer to Extract Sub-Types: infer introduces a temporary type variable inside conditional pattern matching.T = A | B evaluates to (A extends U ? X : Y) | (B extends U ? X : Y)).[T] extends [U] disables union distribution.Write a conditional type Flatten<T> that extracts the element type U if T is an array U[], or returns T if it is not an array.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With