We use cookies for analytics and advertising. Ads are disabled until you accept advertising cookies. Read our Cookie Policy and Privacy Policy.
TypeScript Overloads vs Union Parameters: Which to Use | TVerge Tech
TypeScript Overloads vs Union Parameters: Which to Use
Learn when to use TypeScript function overloads vs union parameters, with real examples, pitfalls, generics alternatives and a clear decision checklist.
TypeScript Function Overloads vs. Union Parameters: Choosing the Right API
You are designing a function that accepts more than one kind of input. TypeScript gives you two obvious tools: function overloads and union parameters. Both look reasonable in a code review, and both compile. The difference shows up later, when a caller passes a value whose type is itself a union, when a return type quietly widens, or when a teammate adds a signature in the wrong position.
This guide explains how each approach works, where each one breaks, and how to choose between them. Every example assumes strict: true in your tsconfig.json, and the guidance follows the official TypeScript Handbook on functions.
Key Takeaways
Use a union parameter when every input produces the same kind of output. It is shorter and accepts union-typed arguments.
Use overloads when the return type depends on which input the caller passed, or when valid argument counts differ.
Consider a generic with a conditional or lookup type when overloads start repeating the same pattern.
Consider a discriminated union or options object when the caller must choose between named modes.
Overload order matters, and the implementation signature is never callable from outside.
Ask one question before writing any signature: does the output type change depending on the input type?
No: use a union parameter.
Yes: use overloads, or a generic that maps input to output.
The rest of this article explains why that rule holds, and what to do when it does not fit cleanly.
How Union Parameters Work
A union type describes a value that can be one of several types. The Handbook's section on union types covers the syntax. Used on a parameter, it keeps the API to a single signature:
function len(x: string | unknown[]): number {
return x.length;
}
len("hello"); // 5
len([1, 2, 3]); // 3
Both string and arrays have a length property, so no narrowing is needed here. When the body needs behaviour that differs by type, you narrow with a typeof check, Array.isArray, or the in operator, as described in the Handbook's narrowing chapter:
This function accepts a single ID or a list and always returns a list. The output type is the same for every input, which is the situation where a union parameter is the cleanest choice.
Strengths of union parameters
One signature to read. Hover text, autocomplete and documentation all show a single declaration.
Union arguments just work. If a caller holds a string | string[], they can pass it straight in.
Less code to maintain. There is no separate implementation signature to keep in sync.
Limitations of union parameters
The return type cannot depend on the input. If you return number | number[], every caller must narrow the result, even when they know which one they get.
Correlated parameters are not expressible. You cannot say "if the first argument is a string, the second must be a number" with independent union parameters.
How Function Overloads Work
An overloaded function has two parts. The overload signatures are the public contract callers see. The implementation signature is the single function body that handles every case. As the Handbook explains, you write the overload signatures first, then one implementation that is compatible with all of them:
function parseInput(input: string): number;
function parseInput(input: string[]): number[];
function parseInput(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const a = parseInput("42"); // number
const b = parseInput(["1", "2"]); // number[]
Here the return type follows the argument. A caller who passes a string gets a number and does not need to narrow. That precision is the main reason overloads exist.
The implementation signature is invisible
This catches many developers the first time. Only the overload signatures are callable. The implementation signature is hidden from callers, even if it is more permissive:
function pad(value: string): string;
function pad(value: number): string;
function pad(value: string | number, width?: number): string {
return String(value).padStart(width ?? 2, "0");
}
pad("7"); // OK
pad("7", 3); // Compile error: no overload accepts two arguments
If you want callers to pass width, it has to appear in an overload signature. The implementation alone does not expose it.
Where Overloads Break Down
Overloads are precise, but that precision has costs. These are the three problems that come up most often.
Problem 1: Overloads reject union arguments
This is the most common surprise, and the Handbook's guidance on writing good overloads exists because of it. TypeScript resolves a call to a single overload. It does not combine two overloads to satisfy a union argument.
function len(s: string): number;
function len(arr: unknown[]): number;
function len(x: string | unknown[]): number {
return x.length;
}
len("hello"); // OK
len([1, 2, 3]); // OK
const value = Math.random() > 0.5 ? "hello" : [0];
len(value); // Error: No overload matches this call
value is string | number[]. It matches neither overload on its own, so the call fails. The union-parameter version of this function has none of this friction:
function len(x: string | unknown[]): number {
return x.length;
}
len(value); // OK
If you must keep overloads and also want to support union arguments, add a third overload that accepts the union:
function parseInput(input: string): number;
function parseInput(input: string[]): number[];
function parseInput(input: string | string[]): number | number[];
function parseInput(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
The third overload is the escape hatch. It returns the wide type because TypeScript cannot know which branch will run.
Problem 2: Order changes behaviour
TypeScript checks overloads from top to bottom and picks the first one that matches. A broad signature placed too early shadows the specific ones below it:
function describe(value: string | number): string;
function describe(value: string): "text"; // never selected
const d = describe("hi"); // d: string, not "text"
Put the most specific overloads first and the most general last:
function describe(value: string): "text";
function describe(value: number): "number";
function describe(value: string | number): "text" | "number" {
return typeof value === "string" ? "text" : "number";
}
const d = describe("hi"); // d: "text"
Order is invisible at the call site and easy to break in a refactor. A code reviewer has to notice that a new signature landed in the wrong place.
Problem 3: The implementation can lie
TypeScript only checks that the implementation signature is compatible with each overload. It does not verify that the body actually returns the right type for each case. This implementation compiles, but it is wrong:
function toList(input: string): string[];
function toList(input: number): number[];
function toList(input: string | number): string[] | number[] {
return ["oops"]; // compiles, but breaks the number overload
}
With a union parameter, a wrong return type is caught directly, because there is a single declared return type to check against.
When Overloads Are the Right Choice
Overloads earn their extra lines in three situations.
1. The return type depends on the input type
This is the core use case, shown in parseInput above. When you would otherwise force callers to narrow a result they already know the type of, overloads remove that burden.
2. Valid argument counts differ
Sometimes a function has distinct call shapes that should not be mixed. A date constructor that accepts either a timestamp or year, month and day is a good example:
function makeDate(timestamp: number): Date;
function makeDate(year: number, month: number, day: number): Date;
function makeDate(a: number, month?: number, day?: number): Date {
if (month !== undefined && day !== undefined) {
return new Date(a, month - 1, day);
}
return new Date(a);
}
makeDate(1700000000000); // OK
makeDate(2024, 3, 15); // OK
makeDate(2024, 3); // Error: invalid shape
A single signature with optional parameters would accept makeDate(2024, 3) and silently build the wrong date. The overloads turn that mistake into a compile error.
A modern alternative is a union of tuple types in a rest parameter, which gives you the same protection with one signature:
function makeDate(
...args: [timestamp: number] | [year: number, month: number, day: number]
): Date {
if (args.length === 1) return new Date(args[0]);
const [year, month, day] = args;
return new Date(year, month - 1, day);
}
TypeScript narrows the tuple union by its length, so the body stays type-safe without an extra implementation signature.
3. You are typing an existing JavaScript API
Library authors often need to describe a function that already exists and already behaves differently by input. Overloads in declaration files are a natural fit because you are describing real behaviour rather than designing a new API.
Alternatives to Consider Before Writing Overloads
Overloads are not the only way to relate inputs to outputs. Two alternatives often produce a better API.
Generics with a lookup type
When the input is a key and the output is looked up from a map, a generic replaces a long list of overloads. The Handbook's generics chapter introduces the underlying idea of relating two values through a shared type parameter:
Adding a new tag means adding one line to TagMap, not another overload. Union arguments also work naturally here, because the generic infers a union and indexes into the map with it.
Generics with a conditional type
When the output is computed from the input type, a conditional type from the Handbook's conditional types chapter can replace two overloads with one signature:
type ParseResult<T extends string | string[]> =
T extends string ? number : number[];
function parseInput<T extends string | string[]>(input: T): ParseResult<T> {
return (Array.isArray(input) ? input.map(Number) : Number(input)) as ParseResult<T>;
}
const a = parseInput("42"); // number
const b = parseInput(["1", "2"]); // number[]
declare const either: string | string[];
const c = parseInput(either); // number | number[]
The union argument works, because the conditional type distributes over string | string[]. The trade-off is that the implementation needs a type assertion, and complex conditional types are harder to read than two short overloads. For two or three cases, overloads are often clearer. For many cases, or cases that follow a pattern, the generic wins. If you want to go deeper on conditional types and satisfies, see our advanced TypeScript tutorial on mapped types, satisfies and conditional types.
Discriminated unions and options objects
Sometimes the real problem is that the caller is choosing between modes, and overloads hide that choice. If each mode takes different data, model the mode explicitly:
type User = { id: string; email: string; name: string };
type UserQuery =
| { by: "id"; id: string }
| { by: "email"; email: string };
function findUser(query: UserQuery): User | undefined {
switch (query.by) {
case "id":
return lookupById(query.id);
case "email":
return lookupByEmail(query.email);
}
}
declare function lookupById(id: string): User | undefined;
declare function lookupByEmail(email: string): User | undefined;
findUser({ by: "email", email: "ada@example.com" });
The call site is self-documenting, a new mode is a new union member, and the compiler checks that every case is handled. For a full walkthrough of this pattern, including exhaustive checks with never, read our guide to TypeScript discriminated unions and type narrowing. If you are modelling data from an API response, the JSON to TypeScript Converter can generate the starting interfaces from a sample payload.
Side-by-Side Comparison
Criterion
Union parameter
Overloads
Generic + conditional type
Signatures to read
One
Several
One, but denser
Accepts union arguments
Yes
No, unless you add a union overload
Yes
Return type follows input
No
Yes
Yes
Order-sensitive
No
Yes
No
Implementation checked per case
Single return type
Loosely
Usually needs an assertion
Best for
Same output for any input
Few distinct call shapes
Many cases following a pattern
Overloads in Classes, Interfaces and Type Literals
Overloads are not limited to standalone functions. Class methods can be overloaded with the same pattern: overload signatures first, one implementation last.
class Store {
get(key: string): string | undefined;
get(key: string, fallback: string): string;
get(key: string, fallback?: string): string | undefined {
return this.data.get(key) ?? fallback;
}
private data = new Map<string, string>();
}
The second overload communicates something a single optional parameter cannot: when a fallback is provided, the result is never undefined.
Note that arrow functions cannot carry overload declarations directly. If you need overloads on an arrow-style function, declare its type with an interface like the one above.
Developer Experience and Error Messages
API design is also about what callers see when they make a mistake.
Hover and autocomplete. An overloaded function shows a counter such as "1/3" in most editors, and callers must cycle through signatures. A union parameter shows one signature.
Error messages. When no overload matches, TypeScript reports that no overload matches the call and typically explains the failure against the last overload, which is not always the one the caller intended. Union parameter errors point at one declaration.
Documentation. With overloads, you can attach a separate JSDoc comment to each signature. That helps when the signatures represent genuinely different operations. It is wasted effort when they do not.
If your overload list grows past three or four entries, treat that as a signal to look at generics or a discriminated union instead.
Testing Your Types
Type-level behaviour can regress just like runtime behaviour. A cheap way to lock in an overload contract is to write calls that must compile and calls that must fail, using // @ts-expect-error:
parseInput("1"); // OK
parseInput(["1"]); // OK
// @ts-expect-error: numbers are not accepted
parseInput(1);
If someone later widens the signature so parseInput(1) becomes valid, the @ts-expect-error line stops being an error and the compiler flags the unused directive. Run tsc --noEmit in CI so these checks execute on every pull request.
Common Mistakes to Avoid
Using overloads when the return type does not change. If every overload returns the same type, a union parameter is simpler and more flexible.
Putting a broad signature first. Specific overloads must come before general ones.
Forgetting that the implementation signature is hidden. Anything callers need must appear in an overload.
Using any in the implementation without checking the body. The compiler will not catch a body that disagrees with an overload, so keep the implementation parameter types as narrow as the union of your overloads.
Growing the overload list indefinitely. Many overloads usually point to a missing abstraction such as a generic map type or a discriminated union.
Skipping the union-argument case. If callers might hold a union value, either use a union parameter or add an overload for the union.
A Practical Decision Checklist
Work through these questions in order:
Does the return type depend on the input type? If no, use a union parameter and stop.
Is the relationship a lookup from a key to a type? Use a generic with a lookup type.
Is the relationship computed from the input type by a pattern? Consider a generic with a conditional type.
Do the valid argument counts or shapes differ, with two or three distinct cases? Use overloads, or a rest-parameter tuple union.
Is the caller choosing a named mode? Use a discriminated union or an options object.
Will callers hold union-typed values? Add an overload that accepts the union, or prefer a union parameter or generic.
Frequently Asked Questions
When should I use overloads instead of a union type in TypeScript?
Use overloads when the return type depends on the argument type, or when different argument counts are valid and mixing them should be an error. When every input produces the same output type, a union parameter is simpler.
Why does TypeScript say "No overload matches this call" for a union argument?
TypeScript resolves a call to one overload and does not combine overloads to satisfy a union. Either add an overload that accepts the union, switch to a union parameter, or use a generic.
Can I call the implementation signature directly?
No. Only the overload signatures are visible to callers. The implementation signature exists to handle the cases the overloads declare.
Does overload order matter?
Yes. TypeScript picks the first overload that matches, so specific signatures should come before general ones.
Can arrow functions be overloaded?
Not with overload declarations. Declare the function's type as an interface with multiple call signatures, or use a regular function declaration.
Are overloads slower than union parameters?
For a handful of signatures the difference is not something you will notice. Very long overload lists can make error messages harder to read and are a maintainability concern long before they become a performance one.
Conclusion
Overloads and union parameters solve overlapping problems, but they are not interchangeable. Union parameters give you a short, flexible signature that accepts union arguments. Overloads give you precise return types and strict argument shapes, at the cost of order sensitivity, hidden implementation signatures and rejected union arguments.
Start with the simplest option that is correct. If the output type is the same for every input, use a union parameter. If the output depends on the input, reach for overloads or a generic. If the caller is choosing between modes, model the modes. Whichever you pick, write a few @ts-expect-error checks so the contract stays intact as the code evolves.