Union Types in TypeScript
2 min read
What do you do when you want a variable to be able to take more than one type? You use
union type. Union types enable you to create a variable that can take a combination of more than one type.
Ideally, you would want to define a unique type for each variable. However, there are times when, for good reason, we will need to allow some room for flexibility. Fortunately, TypeScript makes provision for that. With union types, we can specify multiple types for a single variable.
Syntax for Union Types
Union types are defined by placing the pipe symbol (
|) between the names of the types. The syntax is as follows.
let myVariable: type1 | type2
Let's see some examples below.
let contact: string | number; contact = "firstname.lastname@example.org" contact = 123
In the example above, the
contact variable can take either a string or a number. The above example allows the contact variable to take any of the two types defined. It is also possible for the
union type to include more than just two types.
The union type can be helpful in situations where you aren't sure of the specific type to expect. However, you know that it can only be one of some specific types. As mentioned earlier, this allows you to maintain strictness of type yet with some degree of flexibility.
Thanks for reading.
Let's connect on LinkedIn | Twitter