Course contentsShow
← TypeScript
Lesson 484 of 1,79611. Literal TypesFree lesson

Combining Literal Unions for Complex States

Compose multiple literal unions to model combinations of discrete states in domain logic.

Combining Literal Unions for Complex States

What You'll Learn

You'll learn how to compose multiple literal type unions together to create precise, type-safe representations of complex domain logic with interdependent states.

The Core Idea

Sometimes a single literal union isn't enough to model real-world scenarios. Many domains have multiple independent dimensions that combine to form valid states. For example, a data request might have both a status ("idle" | "loading" | "success" | "error") and a method ("GET" | "POST"). By combining separate literal unions, you create a type-safe grid of possibilities.

Think of it like ordering a custom pizza: you have one union for size ("small" | "medium" | "large") and another for crust ("thin" | "regular" | "thick"). Any combination is valid, and TypeScript ensures you only pick from the allowed options in each dimension.

Creating Combined States

You compose literal unions using intersection types or object types with multiple literal-typed properties:

type Size = "small" | "medium" | "large";
type Crust = "thin" | "regular" | "thick";

type PizzaOrder = {
  size: Size;
  crust: Crust;
};

const order: PizzaOrder = {
  size: "medium",
  crust: "thin"
}; // Valid combination

// TypeScript catches invalid values in either dimension
// const bad: PizzaOrder = { size: "huge", crust: "thin" }; // Error!

Each property narrows independently, giving you autocomplete and safety on both dimensions simultaneously.

When This Pattern Shines

This approach excels for:

  • Request/response state modeling (status + data presence)
  • UI component variants (theme + size + disabled state)
  • Game states (player turn + game phase)
  • Form validation (field name + validation state)

Key Takeaway: Combine multiple literal unions to model domain logic with several independent dimensions, getting type safety and autocomplete across all axes of variation.