TypeScript · Types that pay for themselves
When should you use overloads instead of a union parameter?
Short answer
Overloads model different argument or return relationships; a union parameter is simpler when one implementation handles all cases. Overloads are worth it when the return type depends on the input type.
A union parameter is usually the smaller API. If a function accepts string | string[] and returns the same type for both, one signature is enough. Overloads become valuable when the return type changes based on which argument was passed, because a union signature would force callers to narrow the result.
function parse(value: string): string[];
function parse(value: string[]): string;
function parse(value: string | string[]): string | string[] {
return Array.isArray(value)
? value.join(",")
: value.split(",");
}
const parts = parse("a,b,c");
const joined = parse(["a", "b", "c"]);How to choose
- Use a union when every case returns the same type
- Use overloads when the return type is tied to the input type
- Use a generic conditional type when the relationship is systematic
- Overloads are easier for callers to read than a complex conditional type
- A union is easier to handle exhaustively inside the implementation
Overloads and unions are not mutually exclusive. A common pattern is a small set of overloads backed by one implementation that accepts a union. The overloads document the public call shapes; the union keeps the implementation simple. If the overload list grows beyond a few entries, reconsider the API.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the main advantage of overloads over a union?
- 2When does a generic conditional type beat both?
- 3Can overloads and a union be combined?
- 4How many overloads is too many?
Say it in the interview
A union parameter is usually simpler when one implementation handles every case and returns the same type. Overloads are worth the extra code when the return type changes based on the input, such as parsing a string into an array and an array into a string. I compare the two by asking whether callers need a precise return type per argument. If not, a union keeps the API smaller and easier to exhaustively handle.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.