0
0
Typescriptprogramming~5 mins

Union vs intersection mental model in Typescript

Choose your learning style9 modes available
Introduction

Union and intersection types help you combine different types in TypeScript. They let you describe values that can be one type or another (union) or must have all types together (intersection).

When a value can be one of several types, like a string or a number.
When you want to combine properties from multiple types into one object.
When you want to accept different shapes of data but handle them safely.
When you want to create flexible functions that work with multiple types.
When you want to enforce that a value has all features from multiple types.
Syntax
Typescript
type UnionType = TypeA | TypeB;
type IntersectionType = TypeA & TypeB;

The | symbol means 'or' (union).

The & symbol means 'and' (intersection).

Examples
This means a value can be a string or a number.
Typescript
type StringOrNumber = string | number;
This means a value must have both a name and an age.
Typescript
type Person = { name: string } & { age: number };
Union allows either type, intersection requires both types combined.
Typescript
type A = { a: string };
type B = { b: number };
type C = A | B; // union
// C can be either { a: string } or { b: number }

type D = A & B; // intersection
// D must have both { a: string } and { b: number }
Sample Program

This example shows how union lets you accept either a cat or a dog, while intersection requires both cat and dog features.

Typescript
type Cat = { meow: () => void };
type Dog = { bark: () => void };

// Union: can be Cat or Dog
function speak(pet: Cat | Dog) {
  if ('meow' in pet) {
    pet.meow();
  } else {
    pet.bark();
  }
}

// Intersection: must be both Cat and Dog
function speakBoth(pet: Cat & Dog) {
  pet.meow();
  pet.bark();
}

const cat: Cat = { meow: () => console.log('Meow!') };
const dog: Dog = { bark: () => console.log('Bark!') };
const catDog: Cat & Dog = {
  meow: () => console.log('Meow!'),
  bark: () => console.log('Bark!')
};

speak(cat);      // Meow!
speak(dog);      // Bark!
speakBoth(catDog); // Meow!
Bark!
OutputSuccess
Important Notes

Union types let you work with values that can be different types, but you often need to check which one it is before using it.

Intersection types combine multiple types into one, so the value must have all properties from each type.

Think of union as a choice between types, and intersection as a combination of types.

Summary

Union (|) means a value can be one type or another.

Intersection (&) means a value must have all combined types.

Use union for flexible inputs, intersection for combining features.