Union and Intersection Types
Explore how union and intersection types in TypeScript allow you to combine types effectively by applying set theory principles. Understand the differences and use cases of these types, including practical examples like React props composition. Gain the skills to write more precise and safe type definitions.
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. ...