TypeScript Union Types and Narrowing

A union type such as number | string says a value may be any one of the listed types. You can only use operations that are valid for every member until you narrow the type.

TypeScript
type Id = number | string;

function format(id: Id): string {
  if (typeof id === "number") {
    return `#${id.toFixed(0)}`;
  }
  return id.toUpperCase();
}

console.log(format(42));
console.log(format("ab7"));
Read the full lesson