Conditional types (TypeScript)
An explanation of TypeScript conditional types and an overview of some useful predefined ones
Basic idea
Conditional type: selects one of two possible types based on a condition, where the condition is something that tests for the relationship between types
General structure: T extends U ? X : Y
Examples (adapted from Conditional Types ):
The above were examples where the conditional type is resolved (the compiler can immediately decide what the resulting type is going to be)
Alternatively, the type can be deferred, meaning the compiler will decide when it has more info
Example (adapted from Conditional Types ):
Predefined conditional types
Some conditional types already defined by the TypeScript language (see Predefined conditional types ):
Exclude
— Exclude fromT
those types that are assignable toU
Extract
— Extract fromT
those types that are assignable toU
NonNullable
— Excludenull
andundefined
fromT
ReturnType
— Obtain the return type of a function typeInstanceType
— Obtain the instance type of a constructor function type
Examples (adapted from Predefined conditional types ):