Unions and Intersection Types
So far, the handbook has covered types which are atomic objects. However, as you model more types you find yourself looking for tools which let you compose or combine existing types instead of creating them from scratch.
Intersection and Union types are one of the ways in which you can compose types.
Union Types
Occasionally, you’ll run into a library that expects a parameter to be either a number
or a string
. For instance, take the following function:
The problem with padLeft
in the above example is that its padding
parameter is typed as any
. That means that we can call it with an argument that’s neither a number
nor a string
, but TypeScript will be okay with it.
In traditional object-oriented code, we might abstract over the two types by creating a hierarchy of types. While this is much more explicit, it’s also a little bit overkill. One of the nice things about the original version of padLeft
was that we were able to just pass in primitives. That meant that usage was simple and concise. This new approach also wouldn’t help if we were just trying to use a function that already exists elsewhere.
Instead of any
, we can use a union type for the padding
parameter:
A union type describes a value that can be one of several types. We use the vertical bar (|
) to separate each type, so number | string | boolean
is the type of a value that can be a number
, a string
, or a boolean
.
Unions with Common Fields
If we have a value that is a union type, we can only access members that are common to all types in the union.
Union types can be a bit tricky here, but it just takes a bit of intuition to get used to. If a value has the type A | B
, we only know for certain that it has members that both A
and B
have. In this example, Bird
has a member named fly
. We can’t be sure whether a variable typed as Bird | Fish
has a fly
method. If the variable is really a Fish
at runtime, then calling pet.fly()
will fail.
Discriminating Unions
A common technique for working with unions is to have a single field which uses literal types which you can use to let TypeScript narrow down the possible current type. For example, we’re going to create a union of three types which have a single shared field.
Last updated