Course contentsShow
← TypeScript
Lesson 588 of 1,79614. Generics in PracticeFree lesson

When Not to Use Generics

Recognizing cases where concrete types or unions are simpler and more appropriate.

When Not to Use Generics

What you'll learn: How to recognize when generics add unnecessary complexity and when simpler type solutions are more appropriate.

Generics are powerful, but they're not always the right tool. Sometimes a straightforward concrete type or a simple union makes your code clearer and easier to maintain.

When Simpler Is Better

Overgeneralizing Simple Cases

If your function truly only works with one or two specific types, don't make it generic. A generic type parameter suggests flexibility that doesn't actually exist:

// ❌ Overly generic - only works with numbers anyway
function double<T>(value: T): T {
  return (value as any) * 2; // Type lie!
}

// ✅ Honest and clear
function double(value: number): number {
  return value * 2;
}

When Unions Are Clearer

If you have a known, finite set of types, a union type is often more readable than a generic:

// ❌ Generic obscures what's actually allowed
function format<T>(value: T): string {
  return String(value);
}

// ✅ Union shows exactly what's supported
function format(value: string | number | boolean): string {
  return String(value);
}

The union version immediately tells readers what inputs are valid.

Single-Use Type Parameters

If a type parameter appears only once in your signature, it's probably unnecessary:

// ❌ T adds no value here
function log<T>(message: T): void {
  console.log(message);
}

// ✅ Simple and direct
function log(message: unknown): void {
  console.log(message);
}

The Complexity Test

Ask yourself: "Does this generic enable reuse across different types while maintaining type relationships?" If not, stick with concrete types or unions.

Key Takeaway: Generics should preserve type information across operations; if you're dealing with a fixed set of types or no meaningful type relationships, concrete types and unions are simpler and more maintainable.