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

Published: (March 18, 2026 at 10:08 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

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

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" };

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}`);
}

When to Use Them

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

Related posts

Read more »

Agents in 60 lines of python : Part 3

The Agent Loop The entire AI agent stack in 60 lines of Python. You've seen Claude search files, read them, then search again. ChatGPT with Code Interpreter wri...