Union and Intersection Types

This lesson talks about the two most basic ways of composing types, union and intersection type operators.

Overview

The primary way to compose types in TypeScript is via union and intersection type operations.

We’ve already seen union types in action in this course. I assume that you’re more or less familiar with them, given that they’re ubiquitous in TypeScript. In this lesson, I’d like you to gain an in-depth understanding of union types.

Have you ever wondered where these names come from? While you might have some intuition about what a union of two types is, the intersection is usually not understood well.

To properly understand this lesson, it’s important that you’re familiar with the idea of treating types as mathematical sets. Please read this section if you haven’t yet.

Simple union types

Union type is very often used with either null or undefined.

const sayHello = (name: string | undefined) => { /* ... */ };

For example, the type of name here is string | undefined which means that either a string OR an undefined value can be passed to sayHello.

sayHello("milosz");
sayHello(undefined);

Looking at the example, you can intuit that a union of types A and B is a type that accepts both A and B values.

Union and intersection of object types

This intuition also works for complex types.

Get hands-on with 1200+ tech skills courses.