Search⌘ K

Creating union types

Explore how to create and use union types in TypeScript to combine different types such as numbers, null, undefined, string literals, and objects. Understand how union types can represent multiple possible values, making your React app's types stronger and more precise.

Understanding a union type #

As the name suggests, union types are types that we can combine together to form a new type. A union type is constructed from existing types using the pipe (|) character:

type A_or_B_or_C = A | B | C;

Let’s go through an example to make this clear. Let’s say we have an age variable that can be null or numeric. How could we ...