March 29, 2023
If you've ever worked with logical boolean operators,
OR, then you conceptually already understand union and intersection types.
A union type can be though of as
ORand 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
type Savoury = "chips" | "pizza" | "burgers" | "guacamole" | "cheese" | "salted caramel" | "turkey with cranberry sauce"| "chicken and waffles";
And a type for
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
SavouryOrSweetdoes in fact contain all values from both salty and sweet.
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 }