Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Built-in conditional types

In the preceding section, we have used the ReturnType type to extract the return type of a given function. The ReturnType type is included as a built-in type. TypeScript 2.8 includes many other types:

// Exclude from T those types that are assignable to U
type Exclude<T, U> = T extends U ? never : T;

// Extract from T those types that are assignable to U
type Extract<T, U> = T extends U ? T : never;

// string[] | number[]
type Foo2 = Extract<boolean | string[] | number[], any[]>;

// boolean
type Bar2 = Exclude<boolean | string[] | number[], any[]>;

// Exclude null and undefined from T
type NonNullable<T> = T extends null | undefined ? never : T;

// Obtain the return type of a function type
type ReturnType<T extends (...args: any[]) => any> = T extends (...args: any[]) => infer R ? R : any;

// Obtain the return type of a constructor function type
type InstanceType<T extends new (...args: any[]) => any> = T extends new (...args: any[]) => infer R ? R : any;