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/Parameterssee only the last overload
Code / implementation expected: Yes β a function with two or three overload signatures and one implementation, called in each way.