Union Types

Allow a value to be one of several types using the pipe symbol.

Syntaxlet x: string | number;

A union type uses | to say a value can be one of several types. For example string | number accepts either a string or a number.

Before using type-specific methods, you usually need to narrow the union to a single type with a check like typeof.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A function that accepts both a string path and a URL object uses string | URL as its parameter type.
  • An API response type is string | ErrorResponse to handle both success and failure in one function.
  • A form field value is typed string | number to handle text inputs and numeric inputs from the same interface.

More examples

Basic union type

Accepts either a string or number and narrows with typeof to handle each case appropriately.

Example · ts
function formatId(id: string | number): string {
  return typeof id === 'number' ? `#${id}` : id;
}

console.log(formatId(42));     // '#42'
console.log(formatId('abc')); // 'abc'

Union with null for optionality

Returns an object or null and requires the caller to narrow the null case before accessing properties.

Example · ts
function findUser(id: number): { name: string } | null {
  if (id === 1) return { name: 'Alice' };
  return null;
}

const user = findUser(2);
if (user !== null) {
  console.log(user.name);
}

Union in an array

Stores a mixed array of strings and numbers using a union type alias, then narrows inside forEach.

Example · ts
type StringOrNumber = string | number;

const mixed: StringOrNumber[] = [1, 'two', 3, 'four'];

mixed.forEach((item) => {
  if (typeof item === 'string') {
    console.log(item.toUpperCase());
  } else {
    console.log(item.toFixed(2));
  }
});

Discussion

  • Be the first to comment on this lesson.