Skip to content

Narrowing Unions

Jorge Castro edited this page Nov 10, 2025 · 1 revision

Common issue with unions

In this example, property 'toUpperCase' does not exist on type 'number'

function printId(id: number | string) {
  console.log(id.toUpperCase());
}

The solution is to narrow the union to deduce a more specific type for a value based on the structure of the code.

function printId(id: number | string) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id);
  }
}

Clone this wiki locally