QuestionsTypeScript

Function overloads vs generics vs unions

Function SignaturesMediumTypeScript

When should you use function overloads, and when is a generic or a union parameter the better tool?

What it tests

Choosing the right signature technique so the return type follows the input precisely.

Approach & answer

Overloads let one implementation advertise several distinct call signatures, so the return type depends on which argument shape the caller used — classic for DOM APIs like createElement('a') returning HTMLAnchorElement. But overloads are verbose and the single implementation signature must be a supertype of all of them. Prefer a generic when the relationship between input and output is uniform — the return type is a function of a type parameter (identity, arrays, mapping) — because one generic signature captures infinitely many cases that overloads would have to enumerate. Prefer a plain union parameter when the function accepts several types but treats them the same way and returns a single type; narrow inside with a type guard. Rule of thumb: same transformation over many types -> generic; different return type per input shape -> overload (or a conditional-type generic if the mapping is expressible); many inputs, one output -> union. Overuse of overloads is a smell that a generic or conditional type would be cleaner.

Use this technique when

Modeling APIs whose return type varies by argument (overload); write-once transformations over many types (generic).

References

ts