When Not to Use Generics
You'll learn: How to recognize when a generic adds complexity without adding value, and when simpler types are the better choice.
The Over-Engineering Trap
Generics are powerful, but they're not always the right tool. Sometimes a simple union type or specific type is clearer, easier to maintain, and gets the job done without the cognitive overhead.
Think of generics like a Swiss Army knife—great when you need multiple tools in one, but if you only need to cut paper, regular scissors are simpler and better.
When Simpler Types Win
A single concrete use case: If your function only works with one or two specific types, just use those types directly. Don't create a generic "just in case" you'll need it later.
// Over-engineered with a generic
function getFirstNumber<T extends number>(items: T[]): T | undefined {
return items[0];
}
// Better: just use number
function getFirstNumber(items: number[]): number | undefined {
return items[0];
}
A small, known set of types: If you only handle 2-3 specific types, a union is often clearer than a generic with constraints.
// Generic that doesn't add clarity
function format<T extends string | number>(value: T): string {
return String(value);
}
// Simpler and just as effective
function format(value: string | number): string {
return String(value);
}
No type relationship to preserve: Generics shine when you need to preserve the connection between input and output types. If that relationship doesn't matter, skip the generic.
Key Takeaway: Use generics when you need flexibility across many types while preserving type relationships. Choose specific types or unions when you have a small, known set of cases—clarity beats theoretical reusability.