DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Mastering Union and Intersection Types in TypeScript: Quick Guide with Examples

Union Types:

  • Use union types when a variable or parameter can hold values of multiple types.
  • Syntax: typeA | typeB
  • Example:
let value: string | number;
value = "hello"; // valid
value = 42;      // valid
value = true;    // invalid
Enter fullscreen mode Exit fullscreen mode

Intersection Types:

  • Use intersection types to combine multiple types into one.
  • The resulting type has all properties from each type.
  • Syntax: typeA & typeB
  • Example:
type A = { a: number };
type B = { b: string };
let obj: A & B = { a: 1, b: "hello" };
Enter fullscreen mode Exit fullscreen mode

Key Differences:

  • Union (|): Accepts values that match any member type.
  • Intersection (&): Requires values to satisfy all member types.

Practical Example:
Suppose you have user types:

type Admin = { name: string; admin: true };
type User = { name: string; admin?: false };

type AnyUser = Admin | User;
// Can be either Admin or User

function greet(user: AnyUser) {
  console.log(`Hello, ${user.name}`);
}
Enter fullscreen mode Exit fullscreen mode

When to Use Them:

  • Use unions when data can be of different shapes.
  • Use intersections to combine multiple requirements into a single type.

Top comments (0)