Two ways to combine
TypeScript composes types with two operators. A union written with a bar means one of several types. An intersection written with an ampersand means all of several types at once.
Unions are or
A value typed as string or number may hold either. Until you narrow it, you can only use members common to both. You cannot call a string only method until you prove the value is a string.
Intersections are and
An intersection merges shapes. A value typed as one object type and another must satisfy every property from both. This is how you model an entity that is at once a user and an admin.
How they relate to sets
- A union is the set sum of allowed values, so it is wider and offers fewer guaranteed members.
- An intersection is the set overlap of requirements, so it is narrower and offers more members.
Practical use
Use unions for inputs that arrive in several forms and intersections to compose small object types into a richer one without inheritance.
Key idea
Union means one of these types; intersection means all of them at once, trading breadth for guaranteed members.