Introduction
Typescript union types describe values that can be one of several distinct types. You could imagine an age
variable that could be either a number
or a string
or an acceptTerms
variable that could be a boolean
or a number
.
Let's look at a few examples!
Usage
When declaring a union type you use the type
keyword and the vertical bar (|) to separate each type.
type Age: number | string
We declare a type called Age
which may be both a number
or a string
.
type Person = {
name: string,
age: Age
}
const sally: Person = {
name: "Sally",
age: 40
}
const susan: Person = {
name: "Susan",
age: "30"
}
console.log(typeof(sally.age)) // number
console.log(typeof(susan.age)) // string
Great so we declare a type called Person
that has two properties, name
and age
. Age is of type Age
. We also declare two constants sally
and susan
of type Person
. Sally has an age of type number
and Susan has an age of type string
.
You may also declare a union type inline.
type Person = {
name: string,
age: number | string
}
Union types are not limited to primitive data types. Let's look a union type of two other declared types.
type Lion = {
age: number,
name: string
}
type Elephant = {
age: number,
weight: number
}
type Animal = Lion | Elephant
const lion = {
age: 10,
name: "Leo"
}
const elephant = {
age: 10,
weight: 900
}
const doAnimalThings = (animal: Animal) => {
console.log(animal)
}
doAnimalThings(lion) // { age: 10, name: 'Leo' }
doAnimalThings(elephant) // { age: 10, weight: 900 }
Awesome! We initially declare two types, Lion
and Elephant
. We then declare a union type Animal
that can be, either, a Lion
or an Elephant
. The function doAnimalThings()
accepts a single parameter, animal
, of type Animal
.
Given the definition of the union type, Animal
, we know that the doAnimalThings()
function should work as expected when animal
is of type Lion
or Elephant
.
Note when we declare lion
and elephant
we do not provide a type definition. The Typescript compiler infers the type of the object being passed in as the union type Animal
i.e. either a Lion
or an Elephant
. This ability of the Typescript compiler to infer the type means we can write code against an abstraction and thus polymorphic.
Conclusion
Typescript union types provide a convenient way to get around using the any
type, however, I would suggest using it with caution with primitives.
There are very few reasons why one would require a value to either a string
or a number
and you're more likely to find reasons to declare union types as string | null
.
Happy coding!!!