Skip to content
TypeScript

条件类型

根据条件选择类型。

#conditional-type#advanced-type

Code

typescript
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"