In this lecture, we're going to learn about a feature called Union Types.
They give us more flexibility with annotating data.
We've seen how TypeScript can restrict the type of a variable, either by explicitly setting the type
or letting JavaScript infer the type.
Up until now, we've been stuck with a single type one if we want to allow multiple types.
For example, we may want to retrieve the name from an API.
The initial value for the name may be null until the API request is complete after receiving a response.
We'll update the variable to a string in this scenario.
We would get an error because TypeScript will not allow the data type to change.
One solution would be to add the any type.
The any type is a custom type by TypeScript.
You can think of it as a get out of jail free card.
We aren't restricted to a specific data type with this type.
Unfortunately, we miss out on the benefits TypeScript brings to the table.
There wouldn't be a point in using TypeScript.
That doesn't mean you should never use the any type.
It should be considered as a last resort option.
That leads us to the question What alternative solution is there?
We can add union types.
A union type is when multiple data types are given to a variable, excluding the any type on our variable.
Instead of letting TypeScript infer the type, we can add the string data type back in.
We can add more data types by separating them with a pipe character after the pipe character.
We will add the no data type.
We can add as many data types as we'd like after adding the data type.
Let's try changing the variable to no.
As expected, TypeScript doesn't throw an error if we want to use multiple data types.
We must add the types to the variable TypeScript will not infer union types.
It's up to us to add them in.
Otherwise, we may be restricted to one data type.
One advantage of union types is being able to use them anywhere.
We can add them to functions, return values, arrays and objects.
We're not limited to adding union types to variables.
For example, let's switch over to the example Dot's file.
It's possible the shipping function may fail.
We may want to return a Boolean value for the developer to handle the error if it does.
As of now, we're limited to returning numbers if we want to return numbers and Boolean.
We'll need to add a union type.
We'll update the function by adding the pipe character after the no return type.
Next, we'll add the Boolean type to the list of types.
Just like that, we'll be able to return either a number or Boolean from the function union types are
powerful because of the flexibility they provide.
Let's continue in the next lecture.