TypeScript union types represent multiple types at the same time.
It is convenient to group types into unions to explain they share something in common, they have common purpose (think of redux reducer which receives an action object of many different shapes).
For TypeScript there is an awesome technique called type narrowing
Type narrowing - technique that allows a compiler (and developer via IDE) to understand which exact type (shape) is present inside code block.
How to narrow types
Let's say we have union of two other types like below:
Now, we can narrow type of union via runtime check:
Also, we can narrow type in types context only via built-in utility type Extract:
Also, we create a generic guard which will safely narrow types like that:
Type narrowing via generic guard is especially useful for complex types (shapes) where you need to check multiple fields.