midTypeScript
Explain 'Function Overloads' vs 'Union Types' in API design.
Updated May 4, 2026
Short answer
Unions handle multiple input types independently; Overloads define specific relationships between inputs and outputs.
Deep explanation
Union types are simpler and should be the default choice. However, if the return type of a function changes based on which input type was provided, unions are insufficient. Overloads allow you to describe these pairs (Input A -> Output A, Input B -> Output B). This provides a much stricter and more helpful experience for the caller of the function.
Real-world example
A format function that returns a Date object if a timestamp is provided, but returns a string if a date-string is provided.
Common mistakes
- Writing overloads that are too broad, or forgetting that the final implementation signature is not visible to the caller.
Follow-up questions
- Can you overload arrow functions?