Menu

Union and Intersection Types

Lesson 1: Union and Intersection Types

What is the difference?

|   | Union A | B | Intersection A & B |
| --- | --- | --- |
| Meaning | Either A or B | Both A and B at once |
| A value must have | The properties of one member | The properties of all members |
| You can safely use | Only properties shared by every member (until narrowed) | Every property from all members |
| Typical use | Choices, states, optional data | Combining reusable pieces |

Example

// Union: an ID can be a number or a string
type ProductId = number | string;

function printId(id: ProductId) {
  console.log(id.toString()); // OK: both types have toString
  id.toUpperCase();
  // Error: Property 'toUpperCase' does not exist on type 'number'.
}

// Union of object types
type UpiPayment = { method: 'UPI'; upiId: string };
type CardPayment = { method: 'Card'; last4: string };
type Payment = UpiPayment | CardPayment;

// Intersection: combine reusable pieces
type Timestamps = { createdAt: Date; updatedAt: Date };
type WithId = { id: string };
type StoredProduct = WithId & Timestamps & { name: string; price: number };

const product: StoredProduct = {
  id: 'p1', name: 'Milk 1L', price: 6400,
  createdAt: new Date(), updatedAt: new Date(),
};

How it works

  • With a union, TypeScript only lets you use what is true for every member, until you check which member you have (Lesson 2).
  • An intersection of object types merges their properties.
  • Intersecting incompatible primitives produces never: string & number can never exist.

Common mistakes

Mistake Effect Fix
Expecting `A B` to have all properties of both Property does not exist errors
Intersecting types with conflicting properties Property becomes never Make the shared property types compatible
Very wide unions (`string number boolean

Key takeaways

  • | means "one of"; & means "all of".
  • Unions need narrowing before you use member-specific properties.

Try it: Create an Address type and a ContactDetails type, combine them into DeliveryProfile with &, and create a Discount union of flat and percentage discounts.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details