Using Type Parameters Instead of Union Explosion
You'll learn how to prevent your types from ballooning into dozens of similar variants by using a single generic type instead of explicit unions.
The Union Explosion Problem
When you have multiple related shapes that differ only in a few properties, it's tempting to create a union of explicit types. For example:
A union like:
type StringRequest | NumberRequest | BooleanRequest | DateRequest | ArrayRequest...
This approach doesn't scale. Every new variant requires another type definition, and extracting shared logic becomes painful.
The Generic Solution
Instead of defining similar shapes repeatedly, use a type parameter to capture the varying part. You create one type definition that adapts based on what you pass in:
// ❌ Union explosion
type StringConfig = { type: 'string'; value: string; maxLength: number };
type NumberConfig = { type: 'number'; value: number; max: number };
type BooleanConfig = { type: 'boolean'; value: boolean; strict: boolean };
type Config = StringConfig | NumberConfig | BooleanConfig;
// ✅ Single generic type
type Config<T> = {
type: string;
value: T;
metadata: Record<string, unknown>;
};
// Use it with different types
type StringConfig = Config<string>;
type NumberConfig = Config<number>;
type BooleanConfig = Config<boolean>;
When This Pattern Shines
This pattern is most valuable when:
- Your types share the same structure but differ only in value types
- You need to add new variants frequently without touching existing code
- You want utilities that work across all variants without duplicating logic
The generic approach keeps your type system lean and makes it trivial to support new data types—just instantiate the generic with a new type argument rather than writing yet another union member.
Key Takeaway: Replace unions of similar shapes with a single generic type to keep your type definitions scalable, maintainable, and DRY.