Course contentsShow
← TypeScript
Lesson 550 of 1,79613. GenericsFree lesson

Generic Functions vs Function Overloads

Comparing generic functions with overloaded signatures and choosing the right approach for different scenarios.

Generic Functions vs Function Overloads

What you'll learn: How to choose between generic functions and function overloads when you need flexible, type-safe function signatures.


You've now seen two powerful tools for creating flexible functions: generics and overloads. Both let you write one function that handles multiple input types while preserving type safety, but they solve the problem differently.

When Overloads Win

Function overloads are best when different input types produce fundamentally different output types with no pattern connecting them. Each overload signature describes a specific input-output relationship.

Think of overloads like a menu with distinct dishes: "If you order chicken, you get rice. If you order fish, you get vegetables." Each pairing is independent.

When Generics Win

Generic functions shine when there's a consistent relationship between the input type and output type. The type parameter captures this pattern once, and TypeScript infers it automatically.

Generics are like a photocopy machine: whatever type you put in, you get the same type structure out. The relationship is preserved through the type parameter.

The Key Decision

  • Use generics when the output type depends on the input type in a predictable way (like returning an array of whatever type you passed in)
  • Use overloads when you need specific, unrelated type mappings for different cases (like a function that accepts a number and returns a string, or accepts a boolean and returns an array)

Overloads require you to list every scenario explicitly. Generics let TypeScript figure it out from usage. Generics are often more concise and flexible, but overloads give you fine-grained control when input and output types don't follow a formula.

Key Takeaway: Choose generics when types have a consistent relationship; choose overloads when each input type maps to a specific, unrelated output type.