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
T extends some type
U, then assign
X, otherwise assign
extends keyword is at the heart of conditionals whereby we are checking if every value of
T can be assigned to a value of
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;
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,
StringOrNot could be expanded such that it will no longer be limited to just
SomeType to test against
type StringOrNot<T> = T extends string ? string : never;
This piece will explore the following topics of conditional types :
- Working with conditionals and union types and how they are used with common tasks in TypeScript.
- The differences between checking over the distribution of a union type versus non-distributive types. The difference between the two methods will be explained.
- Some of the TypeScript utility types will be explored, covering how they use conditional types to achieve their logic.
Let’s get started with union types and how they fit into the conditional type puzzle.