Unions Widen, Generics Narrow
What you'll learn: How union parameters force you to handle multiple types broadly, while generics preserve exact types for narrow, specific handling.
The Core Concept
When you write a function, you have two fundamentally different ways to accept multiple types:
- Union parameters say "I accept type A or type B, but I'll treat the input as either possibility inside my function."
- Generic parameters say "Tell me exactly what type you're passing, and I'll remember it throughout the function."
Unions widen your handling—you must write code that works for all possible types in the union. Generics narrow your handling—you preserve the specific type and can return or manipulate it precisely.
Unions Force Broad Handling
function processValue(value: string | number): string | number {
// Inside here, TypeScript knows value is "string | number"
// You can only use operations that work for BOTH types
if (typeof value === "string") {
return value.toUpperCase(); // Narrowed to string
} else {
return value * 2; // Narrowed to number
}
}
const result1 = processValue("hello"); // Type: string | number
const result2 = processValue(42); // Type: string | number
Notice the widening: even though you passed a string, TypeScript returns string | number. You've lost the specificity. The union forces you to handle all cases, and the return type reflects that uncertainty.
Generics Preserve Specificity
function wrapValue<T>(value: T): T {
// TypeScript remembers the EXACT type you passed
return value;
}
const result3 = wrapValue("hello"); // Type: "hello" (literal!)
const result4 = wrapValue(42); // Type: 42 (literal!)
The narrowing happens because T captures the precise type. If you pass "hello", T becomes "hello". The function preserves and returns that exact type.
When Each Pattern Fits
- Use unions when your function genuinely needs to handle distinct cases differently and the output type depends on runtime logic.
- Use generics when you want to accept any type, preserve it, and return or manipulate it without losing type information.
The Mental Model
Think of unions as a wide net—you catch multiple types but must handle them all. Generics are a precise mold—they capture the exact shape and preserve it through your function.
Key Takeaway: Union parameters widen your type handling to cover all possibilities, requiring runtime checks. Generics narrow by preserving the exact type passed in, enabling type-safe, specific operations without widening.