← Lessons

quiz vs the machine

Gold1340

Frontend

Union and Intersection Types

Combine types with or and and to model real data shapes.

4 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. On a value typed as string or number, what can you use before narrowing?

2. What must a value satisfy to match an intersection of two object types?