Back

Union Types

Union types let a variable hold more than one type. Use the | symbol to say "this can be A or B."

// Can be string or number
let id: string | number
id = "abc123"  // OK
id = 42        // OK

// Function that accepts multiple types
function display(value: string | number): void {
  console.log(value.toString())
}

// Type guard: check which type it is
function process(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase())
  } else {
    console.log(value * 2)
  }
}

Roadmap