Extracting Shared Structure from Union Members
What you'll learn: How to identify common properties across union type members and refactor them into reusable base types with smaller, focused variants.
When working with union types—especially discriminated unions—you'll often find that many members share common properties. Repeating these shared properties across every variant creates maintenance headaches and obscures the real differences between variants.
The Problem with Repetition
Imagine modeling different API response types. Each might have status, timestamp, and requestId fields, but differ in their data structure. Writing out all shared properties for every variant is tedious:
type UserResponse = {
status: number;
timestamp: string;
requestId: string;
data: { userId: string; name: string };
};
type ProductResponse = {
status: number;
timestamp: string;
requestId: string;
data: { productId: string; price: number };
};
type ErrorResponse = {
status: number;
timestamp: string;
requestId: string;
error: string;
};
The repetition makes refactoring painful. If you need to add version: string to all responses, you must update every single type.
Extract the Base, Specialize the Variants
Instead, identify the shared structure and extract it into a base type. Then create smaller variant types that only describe their unique properties:
type BaseResponse = {
status: number;
timestamp: string;
requestId: string;
};
type UserResponse = BaseResponse & {
data: { userId: string; name: string };
};
type ProductResponse = BaseResponse & {
data: { productId: string; price: number };
};
type ErrorResponse = BaseResponse & {
error: string;
};
type ApiResponse = UserResponse | ProductResponse | ErrorResponse;
Now BaseResponse captures what's common. Each variant focuses only on what makes it unique. Changes to shared structure happen in one place.
When This Pattern Shines
This approach excels when:
- You have multiple union members with overlapping properties
- The shared structure is semantically meaningful (represents a coherent concept)
- You anticipate changes to the common structure
Avoid over-engineering with base types when variants truly have nothing in common—sometimes a straightforward union is clearest.
Key Takeaway: Extract common properties into a base type and use intersections to create focused variants, reducing duplication and centralizing shared structure changes.