Conditional types | Typescript
TypeScript 2.8 introduces conditional types
The type above means when T is assignable to U the type is X, otherwise the type is Y.
Distributive conditional types#
Then the last line is equivalent to:
Diff example#
Filter example#
Type inference in conditional types#
Within the extends clause of a conditional type, it is now possible to have infer declarations that introduce a type variable to be inferred.
Conditional types can be nested to form a sequence of pattern matches that are evaluated in order:
Predefined conditional types#
TypeScript 2.8 adds several predefined conditional types to lib.d.ts:
Exclude<T, U>-- Exclude fromTthose types that are assignable toU.Extract<T, U>-- Extract fromTthose types that are assignable toU.NonNullable<T>-- ExcludenullandundefinedfromT.ReturnType<T>-- Obtain the return type of a function type.InstanceType<T>-- Obtain the instance type of a constructor function type.
Example#
Note: The
Excludetype is a proper implementation of theDifftype suggested here. We've used the nameExcludeto avoid breaking existing code that defines aDiff, plus we feel that name better conveys the semantics of the type.