TypeScript: Conditional Types Explained
Learn what conditionals are and how they are used in TypeScript
Conditionals in TypeScript, also introduced in the TypeScript handbook, allow us to deterministically define types depending on what parameterised types consist of. The general basic rule is:
type ConditionalType = T extends U ? X : Y
If parameter T
extends some type U
, then assign X
, otherwise assign Y
.
The extends
keyword is at the heart of conditionals whereby we are checking if every value of T
can be assigned to a value of U
. If T
is assignable to U
, then the “true type” will be returned — X
is our case. If T
is not assignable to U
, then the false type, Y
, will be returned.
As a basic example, consider checking whether some type extends a primitive such as a string
, and assign never
if it does not:
type StringOrNot = SomeType extends string ? string : never;
The never
keyword indicates that a value will never occur — we will cover never
in more detail further down when conditionals are used to coincide with type filtering.
Conditionals are often coupled with generic types (otherwise termed type parameters) to test whether such parameter meets a certain condition. With one generic type…