Union Types
Union Types are similar to intersections as they are a combination of types to form a single type. Union types differ, however, in that they do not merge your types but provide or
type functionality instead of an and
type functionality, which was the case with intersection types. This works in a similar way to the ternary operator in JavaScript, where the types you are combining are separated by the |
pipe. If this is confusing, it will all become clear as we move on to an example. We will also take a look at type guards, which is a pattern that will play a major role in the app use of union types. First, consider the following visual representation of a union type:
In the preceding diagram, we have a basic diagram of a union type assignment, where Age
can be of the number
or string
datatypes. You can have union types with more than two options and non-primitive types. This gives you the option...