Breaking Down Large Unions into Semantic Groups
What you'll learn: How to use intermediate type aliases to organize large union types into meaningful, readable groups that improve code maintainability.
The Problem
Imagine you're building a type system for a complex application that handles dozens of different state variants. You might end up with something like this:
type AppState =
| { kind: "idle" }
| { kind: "loading" }
| { kind: "authenticating" }
| { kind: "authenticated"; user: string }
| { kind: "error"; message: string }
| { kind: "networkError"; code: number }
| { kind: "validationError"; fields: string[] }
| { kind: "success"; data: string }
| { kind: "partial"; progress: number }
| { kind: "retrying"; attempt: number };
This works, but it's difficult to scan and understand. The union doesn't communicate the conceptual grouping of these states.
Introducing Semantic Grouping
Instead of one massive union, break it down into intermediate type aliases that represent semantic categories:
type IdleState = { kind: "idle" };
type LoadingState = { kind: "loading" };
type ProgressState = { kind: "partial"; progress: number };
type NetworkingStates = IdleState | LoadingState | ProgressState;
type AuthenticatingState = { kind: "authenticating" };
type AuthenticatedState = { kind: "authenticated"; user: string };
type AuthStates = AuthenticatingState | AuthenticatedState;
type GenericError = { kind: "error"; message: string };
type NetworkError = { kind: "networkError"; code: number };
type ValidationError = { kind: "validationError"; fields: string[] };
type ErrorStates = GenericError | NetworkError | ValidationError;
type SuccessState = { kind: "success"; data: string };
type RetryingState = { kind: "retrying"; attempt: number };
type AppState = NetworkingStates | AuthStates | ErrorStates | SuccessState | RetryingState;
Benefits
Readability: Anyone reading your code immediately understands that errors, authentication, and networking are distinct concerns.
Documentation: The group names serve as inline documentation explaining the relationships between variants.
Reusability: You can use ErrorStates elsewhere in your codebase without redefining all three error types.
Refactoring: Adding a new error type means updating only ErrorStates, not hunting through a giant union.
When to Apply This Pattern
Use semantic grouping when you have more than 5-7 variants in a union, or when variants naturally cluster by domain concept. Don't over-engineer tiny unions—type Status = "pending" | "done" doesn't need grouping.
Key Takeaway: Large unions become maintainable when you use intermediate type aliases to group related variants by their semantic meaning, transforming a flat list into a hierarchical structure that communicates intent.