1. The Core Idea

That’s the essence β€” but let’s go deeper because behavior changes depending on how you use them.


🎯 2. Union Types β€” β€œEither this or that”

A union type allows a variable to hold one of multiple possible types.

βœ… Example 1: Simple Union

let id: string | number;

id = "abc123"; // βœ… okay
id = 101;      // βœ… okay
id = true;     // ❌ error

🧠 Meaning β†’ id can either be a string OR a number, not both at once.


βœ… Example 2: With Functions

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); // βœ… safe
  } else {
    console.log(id.toFixed(2)); // βœ… safe
  }
}

Here TypeScript forces you to narrow down the type before you use it.

That’s called Type Narrowing β€” a key TS feature.


βœ… Example 3: With Interfaces

interface User {
  name: string;
}

interface Admin {
  admin: boolean;
}

function getDetails(person: User | Admin) {
  // You can only access common properties
  // person.name ❌ (not allowed β€” because Admin might not have 'name')
  // person.admin ❌ (not allowed β€” because User might not have 'admin')

  // You must narrow type first:
  if ("name" in person) {
    console.log("User:", person.name);
  } else {
    console.log("Admin:", person.admin);
  }
}

🧩 Important point:

Union narrows access β€” you can only use common members until you check which one it actually is.