Union Types

One of Several Types

A union A | B means "either A or B". You can only use members that exist on all types of the union until you check which one you have.

Example

type OrderId = number | string;

function printId(id: OrderId): void {
  if (typeof id === "string") {
    console.log("Order", id.toUpperCase());
  } else {
    console.log("Order #" + id.toFixed(0));
  }
}

printId(1042);
printId("od-77ab");

Output

Order #1042
Order OD-77AB

Using a Union Without Checking

Example

toUpperCase exists only on string, not on number (TS2339).

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

Compiler output (tsc)

Line 2: error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

Union of Object Types

Example

Use the in operator to check which object you have.

type Card = { cardNumber: string; expiry: string };
type Upi = { vpa: string };

function describe(payment: Card | Upi): string {
  if ("vpa" in payment) return "UPI " + payment.vpa;
  return "Card ending " + payment.cardNumber.slice(-4);
}

console.log(describe({ vpa: "priya@okbank" }));
console.log(describe({ cardNumber: "4111111111111111", expiry: "12/28" }));

Output

UPI priya@okbank
Card ending 1111