Aliasing Union Types
What you'll learn: How to use type aliases to give clear, meaningful names to complex union types.
The Problem with Inline Unions
You've already learned that TypeScript lets you combine types with the | operator. But when you use unions directly in your code, things can get messy fast:
function handleResponse(response: { success: true; data: string } | { success: false; error: string }) {
// ...
}
function logResponse(response: { success: true; data: string } | { success: false; error: string }) {
// ...
}
Notice the repetition? If you need to change the union structure, you'd have to update it in multiple places. That's error-prone and hard to read.
Type Aliases to the Rescue
Type aliases excel at naming complex unions. Instead of repeating the same union everywhere, give it a descriptive name:
type ApiResponse =
| { success: true; data: string }
| { success: false; error: string };
function handleResponse(response: ApiResponse) {
// ...
}
function logResponse(response: ApiResponse) {
// ...
}
Now ApiResponse is self-documenting. Anyone reading your code immediately understands what values are valid without parsing the entire union structure.
Why This Matters
Think of type aliases for unions like variable names in math. Instead of writing 3.14159... everywhere, you write π. The alias:
- Reduces repetition — define once, use everywhere
- Improves readability —
Resultis clearer thanSuccess | Failure - Makes refactoring safer — change the union in one place
- Documents intent — the name explains what the union represents
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Status = 'pending' | 'active' | 'complete';
These names tell you exactly what the union represents, making your code self-documenting.
Key Takeaway: Type aliases transform unreadable inline unions into clear, reusable, self-documenting types that make your codebase easier to understand and maintain.