Union of Types in TypeScript
It happens that a variable can take values of different types. You already know that in this case you can declare this variable with the type any
.
However, there are situations when we know that a variable can take values of not all types, but only some. For example, it can be either a string or a number.
In this case, it would be better to allow the variable to accept only the required types. This is done using union operator of types, representing a vertical stick.
Let's use this operator to allow a variable to be either a string or a number:
let test: string | number;
Let's check - write a number into a variable:
test = 123;
Now let's write the following line into it:
test = 'abc';
Now let's write down the logical value:
test = true; // there will be an error
Make a variable that can be either a number or null
.
Make a variable that can be either a number, a string, or a boolean.