Skip to main content
← TypeScript Lesson 4 / 4

One Variable, Two Types

A value can be more than one type at once — like string | number ("a string OR a number"). That's a union. Before you check, TypeScript only knows it's one of them. But ask a question like typeof x === 'string', and INSIDE that branch TypeScript narrows it down to exactly one type — and lets you use that type's methods safely.

The function

function format(x: string | number) {
  // here x is: string | number
  if (typeof x === "string") {
    // here x is: string
    return x.toUpperCase();
  } else {
    // here x is: number
    return x.toFixed(2);
  }
}

Where is the cursor?

Guard style

The guard if (typeof x === 'string') splits the union into the matching half on each side.

The narrowing funnel

string | number
(not narrowed yet)

Type of x HERE

string | number

Still the whole union — TypeScript can't be sure which one it is yet.

Methods you can call

Almost none — on the raw union string | number you can only use what every member shares. Narrow first to unlock a type's methods.

One variable, written once — but its type changes per branch. The checker tracks the narrowed type wherever the cursor stands.