March 29, 2023
If you've ever worked with logical boolean operators,
AND
and OR
, then you conceptually already understand union and intersection types.Union Types
A union type can be though of as
OR
and when used it's like stating, for instance, I want 'everything from group A and everything from group B'. If you look at the following venn diagram you'll see we are comparing two categories: savoury and sweet. If we were to use TypeScripts union type to declare we want anything that is savoury or sweet we'd get everything you see listed.We can confirm this in TypeScript's playground. First, using the union type
|
, we create a Savoury
type:type Savoury = "chips" | "pizza" | "burgers" | "guacamole" | "cheese" | "salted caramel" | "turkey with cranberry sauce"| "chicken and waffles";
And a type for
Sweet
:type Sweet = "ice cream" | "chocolate" | "cake" | "juice" | "pancakes" | "salted caramel" | "turkey with cranberry sauce" "chicken and waffles";
And finally a type where we declare we want items from either category:
type SavouryOrSweet = Sweet | Savoury;
And hovering over that we can confirm that our new type
SavouryOrSweet
does in fact contain all values from both salty and sweet.Intersection Types
Continuing with the Venn diagram above, if we were to create the following type:
type SavouryAndSweet = Sweet & Savoury;
We will only end up with the items that are in the central, overlapping part
{
salted caramel, turkey with cranberry sauce, chicken and waffles }
...