Skip to content
BENIBIX Learn

Union Type

Also known as Union Types, Sum Type, Either Type

A type for a value that can be one of a few kinds. It may be text or a number.

Think of it like

It is like a box marked toys or books. You know it holds one of the two, and nothing else.

Example

An id field can hold 42 or "A-42". Lucy types it as number | string, and the checker makes her handle both.

Why it matters

Real data often comes in more than one shape. A union names every shape, so none is forgotten.

Definition

A union type says a value can be one of a few types. In TypeScript, string | number means a string or a number. The type checker then makes you handle each case before you use the value. Unions are also how many languages say a value may be missing, like string | null. Rust and Swift build the same idea into enums.

Example code

typescript
function show(id: number | string) {
  if (typeof id === "number") return id.toFixed(0);
  return id.toUpperCase();
}
The value is a number or a string. Each branch handles one case.
A union type is a string or a number. The value fits one door or the other.

Common mistake

Using a union, then treating the value as one type only. The checker stops that, so handle each case.

Key takeaways

  1. 1
    One of a few. The value is this type or that one.
  2. 2
    Check, then use. Each case is handled on its own.
  3. 3
    Missing values. Often written as a type or null.

Compare