Skip to content

Union Types

When a value could be one of several types, use | to combine them.

function printId(id: string | number) {
  console.log(`ID: ${id}`);
}

printId(101); // works
printId("abc"); // works
printId(true); // Error: boolean isn't string | number

You can only use methods that exist on all types in the union:

function printId(id: string | number) {
  console.log(id.toUpperCase()); // Error: toUpperCase doesn't exist on number
}

Narrow the type first:

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); // now it's safe
  } else {
    console.log(id.toFixed(2)); // id is number here
  }
}