Search⌘ K
AI Features

Union with Types and Tagged Union

Explore how to define variables and functions with union types in TypeScript, allowing multiple possible types while maintaining type safety. Understand the use of tagged unions to differentiate between types in complex unions, enabling safer and clearer type narrowing in your code.

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 ...