TypeScript by Example

Union Types

Union, intersection, and literal unions, the building blocks for TypeScript variant modeling.

A union type says "this value is one of these types." TypeScript narrows the union before you use member-specific behavior.

The | operator creates a union. Check the value before calling methods that only exist on one member.

type StringOrNumber = string | number;
 
function format(value: StringOrNumber): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

The & operator creates an intersection. Literal unions model a closed set of allowed values.

type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
 
type Status = "pending" | "active" | "deleted";
 
function handleStatus(status: Status): string {
  if (status === "active") return "User is active";
  return `Status: ${status}`;
}

In production

String literal unions are safer than enums for most flags and API variants. They serialize as plain strings, need no runtime import, and set up the next pattern: discriminated unions for object variants.

Enjoyed this? Get more software craft delivered to your inbox.