TypeScript
Conditional Types
Select types based on conditions.
By EZ4Code Team
conditional-typeadvanced-type
Code
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
// infer extracts types
type Unpack<T> = T extends Promise<infer U> ? U : T;
type R = Unpack<Promise<number>>; // number
// Distributive conditional types
type Exclude2<T, U> = T extends U ? never : T;
type Result = Exclude2<"a" | "b" | "c", "a">; // "b" | "c"Explanation
Conditional types dynamically determine the output type based on the input type.