Skip to the solution
MediumFrontend9 min read

What are function overloads?

365 views

The problem

Question presented to candidate: "What are function overloads in TypeScript? Write a function whose return type depends on how it is called, and tell me when you would use overloads instead of a union parameter or a generic."

What a strong answer should cover:

  • Overloads are several call signatures (bodiless declarations) followed by one implementation; callers see only the overload signatures, never the implementation signature
  • Resolution goes top to bottom and picks the first overload that matches, so specific signatures must come before general ones
  • The implementation signature must be compatible with every overload, or tsc reports TS2394
  • A union-typed argument matches no single overload: overloads do not combine, which is a common surprise
  • Alternatives: a union parameter when the return type does not depend on the input, a generic (possibly with a conditional return type) when it does in a regular way; overloads for a few distinct, irregular shapes
  • Where overloads appear: methods, overloaded call signatures in a type (usable with arrow functions), and the fact that ReturnType / Parameters see only the last overload

Code / implementation expected: Yes β€” a function with two or three overload signatures and one implementation, called in each way.

  • overloads

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptOverload signatures, ordering and compatibility
TypeScriptAlternatives, overloaded call signatures and ReturnType

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 50 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is a polymorphic 'this' type?

Continue