Union with Types and Tagged Union
In this lesson, we will see the union type and the tagged union.
We'll cover the following
Union type
The union type is more common because it’s often used to indicate that a variable can be one type or another. For example, a member could be a string or undefined. Union types are the strongly-typed way to allow multiple types for a function too.
If you have a function that can take a string or an object and depend on the type acting differently, a union can do the job. The any
type would also work, but the problem is that any
allows everything while in reality, you only want to have a limited type of parameters. With any
, you wouldn’t catch if something was not assigned correctly until runtime, but with the union, it’s at compilation time. The return type of a function can also be a union. A function may return a specific object or undefined, for example, or return a number or a string.
Get hands-on with 1200+ tech skills courses.