Creating union types
In this lesson, we'll learn what a union type is, how to create one and some cases where they are useful.
We'll cover the following
Understanding a union type #
As the name suggests, union types are types that we can combine together to form a new type. A union type is constructed from existing types using the pipe (|
) character:
type A_or_B_or_C = A | B | C;
Let’s go through an example to make this clear. Let’s say we have an age
variable that can be null
or numeric. How could we create a type for this? Well we can combine the number
and null
types in a union type as shown below:
Get hands-on with 1400+ tech skills courses.