TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol (
|) between each type.
let random: string | number | Date | Blob;
Defining Specific Values as Types
In our previous example, the variable
random can store a
Date, or a
Blob object. You can also define a specific string value as a union type. One good example is in the case you have a variable called
carStyles , and you only want to get car styles as values such as Sedan, SUV, Truck, etc.
let carStyles: 'Sedan' | 'SUV' | 'Truck';
At first, you might think you could add a string. However, attempting to assign a string a value different from the type options defined to the
carStyle will lead to an error similar to the following:
error TS2322: Type '"a"' is not assignable to type '"Sedan" | "SUV" | "Truck"'
Nowadays, IDEs are powerful enough to make the development experience smooth. For those who like using Visual Studio Code, if you attempt to assign a value to the
carStyles variable, the IDE will display a dropdown with a list of valid options.
In this case, I used only strings as types. However, you could define any kind of type such as a random number or a date.
let random: 'foo' | 2 | 'bar' | 5 | Date ;
Should I Use Union Types?
As previously mentioned, TypeScript includes union types as a way to give you the flexibility you need to handle different logical scenarios. For example, if you are storing CSS property values such as
margin, you will see you could get values as a
string or as a
number. In the case of
margin you could get different values such as
8, and all of them are still valid values.