Recently, I decided to brush off an old project and tune it up with some modern day Typescript know-how. In my weeks-long dice-driven fugue state, I stumbled on some Typescript features that I hadn't had a chance to use before, and I think they're neat.
This post is for TypeScript developers who want a function's return type to follow its input. It shows TypeScript function overloading on one small function, addTwo. Function overloading means giving one function more than one signature, so the compiler knows which return type goes with which argument types. That matters on a shared codebase, because each caller gets a string or a number back instead of a union. After the original post, newer sections cover the basic syntax, the compiled JavaScript, the implementation signature and classes. Later ones cover the TypeScript handbook's rules, Parameters and ReturnType, and when a union type fits better.
A Strange Program#
Let's imagine that you have been asked to write a very interesting, if a little curious, program. Your task is to write a program that will take either a number (4), or a number-like string ("4"). It's then going to add 2 to that number, and return the total. Stranger still, the type of the return value must match the type of the value that you put into the system in the first place.
How would we go about writing something like that? Maybe something like this:
export function addTwo(baseNumber: string | number): string | number {
const baseNumberValue = Number(baseNumber)
if (Number.isNaN(baseNumberValue)) {
throw new TypeError('baseNumber must be number or number-like string')
}
const numericTotal = baseNumberValue + 2
return typeof baseNumber === 'string' ? String(numericTotal) : numericTotal
}Running the program, we see that it works:
addTwo('2') // '4'
addTwo(2) // 4
addTwo(2) // 4What happens if we try to use this elsewhere? Then we get into trouble.
For instance, this line will not work:
addTwo(2) + 4 // Type Error: Operator '+' cannot be applied to types 'string | number' and 'number'.This is because the return type of addTwo is a union type, just like the baseNumber argument. That means that Typescript lacks the understanding that we contextually know just by reading the code: if it's a string coming in, it's a string coming out.
Enter: Overloads#
By re-defining the function signature above the function, we can let Typescript know that there are more specific ways of calling this particular function. This is called "overloading" the function: giving a function more than one function signature. We can construct the overload like so:
export function addTwo(baseNumber: string): string
export function addTwo(baseNumber: number): number
export function addTwo(baseNumber: string | number) {
const baseNumberValue = Number(baseNumber)
if (Number.isNaN(baseNumberValue)) {
throw new TypeError('baseNumber must be number or number-like string')
}
const numericTotal = baseNumberValue + 2
return typeof baseNumber === 'string' ? String(numericTotal) : numericTotal
}The first two changes are the overloads, which spell out the consequences of using one type versus the other. On top of the obvious compiler usability benefits, I really like how this spells it out to any developers who might come across this very odd little function in the future.
On top of that, we've also made a change to the implementation function signature by removing the explicit type returns. While I generally like being explicit about return types, this is one instance where being too explicit hurts us.[1]
A Little Bit of a Tangent (About Overloads and Return Types) but stick with me here#
By explicitly returning the type from this overloaded function's implementation signature, we are clobbering our local Typescript's ability to help us catch problems. Externally, the implementation signature isn't broadcast to any consumers. Only the overload signatures are. However, if we aren't careful, we can make a liar out of ourselves.
Let's imagine our function, with explicit return values in our implementation signature:
+ export function addTwo(baseNumber: string): string
+ export function addTwo(baseNumber: number): number
+ export function addTwo(baseNumber: string | number): string | number {
- export function addTwo(baseNumber: string | number) {
const baseNumberValue = Number(baseNumber)
if (Number.isNaN(baseNumberValue)) {
throw new TypeError('baseNumber must be number or number-like string')
}
const numericTotal = baseNumberValue + 2
return typeof baseNumber === 'string' ? String(numericTotal) : numericTotal
}and now, let's imagine that we accidentally flip the script on that ternary condition on the end. We delete it, and accidentally screw up our cases. Now, we return a string for a number, and a number for a string.
This:
return typeof baseNumber === 'string' ? String(numericTotal) : numericTotalBecomes This:
return typeof baseNumber === 'number' ? String(numericTotal) : numericTotalIdeally, we'd want Typescript to scream at us: "Hey! Your code can never match these type signatures. Stop!" but it never does. This is because internally (when writing the function, in our editors) Typescript looks to the implementation signature for its return data. It is only about to get as specific as its explicit return value allows, and even though we've swapped the cases on the logic gate, it still reads as number | string. This stinks for us, but it stinks extra hard for anyone consuming this function. Because of our explicit-type-clobbering, we've actually made Typescript tell a lie, and it will result in an error that we won't find until runtime.
This is Typescript. We are better than that.
By removing the explicit return, we let the overloads take full responsibility for reporting their validity to us, the developer. This makes sense, if you think about it. Explicit return types are for communicating what Typescript can't assume on its own (or for being friendly to future developers and clear with intent for yourself). You are still explicitly returning a type value here. You're just doing it in the overloads, which is the only thing that gets broadcast to consumers of the function anyway!
Highway to the Overload#
By leveraging specificity in our Typescript, we can nudge and shove future developers towards a deeper understanding of the impact of our code, and let Typescript make sure that we aren't bumping into things along the way.
addTwo(2) + 4 // 8 - no Type errors here!
addTwo('2') + ' Letter Word' // '4 Letter Word'
addTwo('2') + 4 // Type Error - no go, BusterSometimes, the best documentation is the kind that reads you.
And I like our little function! It's strange (and I can't for the life of me imagine what practical use it could have) but I like it, and I wouldn't change a thing.
export function addTwo(baseNumber: string): string
export function addTwo(baseNumber: number): number
export function addTwo(baseNumber: string | number) {
const baseNumberValue = Number(baseNumber)
if (Number.isNaN(baseNumberValue)) {
throw new TypeError('baseNumber must be number or number-like string')
}
const numericTotal = baseNumberValue + 2
return typeof baseNumber === 'string' ? String(numericTotal) : numericTotal
}... ... ...
Okay. Maybe a few things. Next up: Let's get rid of that TypeError with the power of template literals!
What is TypeScript function overloading, and what is its basic syntax?#
TypeScript function overloading is writing two or more overload signatures for the same function, followed by one function body that handles each case. The handbook's More on Functions chapter starts from plain JavaScript: "Some JavaScript functions can be called in a variety of argument counts and types." It goes on: "we can specify a function that can be called in different ways by writing overload signatures." Callers then get multiple ways to call one function, each with its own parameter types and return type. The post's main reason for function overloading is its rule: "if it's a string coming in, it's a string coming out."
The basic syntax has three parts, in this order. The handbook's recipe is to "write some number of function signatures (usually two or more), followed by the body of the function".
- Overload signatures. Each one names the parameter types and a return type, and has no function body. In
addTwothe two overload signatures are(baseNumber: string): stringand(baseNumber: number): number. - The implementation signature. It opens the actual implementation, right after the overloads. In
addTwoits parameter isstring | number, the two input types above it. - The function body. One block of code handles both cases. In
addTwoit checkstypeof baseNumber, then returns a value of type string or type number.
The handbook's makeDate example names the parts the same way. It says "These first two signatures are called the overload signatures." It then adds: "Functions have an implementation signature, but this signature can't be called directly."
The payoff is type safety where the function gets called. With the overloads in place, a number argument gives back type number, so addTwo(2) + 4 passes the type check. TypeScript 7.0.2 confirms it.
Does function overloading in TypeScript create more than one JavaScript function?#
Function overloading in TypeScript leaves one JavaScript function. The TypeScript compiler removes the overload signatures, and that one function is left to run. Compiled with TypeScript 7.0.2 (target ES2020) on November 17, 2026, this post's overloaded addTwo comes out as a single function that starts export function addTwo(baseNumber) {. The two overload lines and the type annotations are gone from the output.
The multiple signatures exist for the type checker, and one implementation is what ships. So function overloading lives in the type system, and the single implementation does the work at run time. It has to handle a string and a number by itself. That is why the body of addTwo checks typeof baseNumber before it returns.
Why can't callers use the implementation signature?#
Callers can't use it because TypeScript hides it, so each call has to match one of the overload signatures. The handbook's section on overload signatures and the implementation signature calls this "a common source of confusion". Its example has one overload that takes a string and an implementation that takes no arguments. This code is copied from that section.
function fn(x: string): void;
function fn() {
// ...
}
// Expected to be able to call with zero arguments
fn();The call gives the error message "Expected 1 arguments, but got 0." TypeScript 7.0.2 reports the same error on the same code. The handbook explains that "the signature used to write the function body" is hidden from callers. TypeScript does not merge overloads to fit a call either, since it "can only resolve a function call to a single overload". The post makes the same point about addTwo: "Externally, the implementation signature isn't broadcast to any consumers."
Does method overloading work on classes and constructors?#
Method overloading works on classes and constructors, and both kinds compiled with no errors in TypeScript 7.0.2. A class method version of this post's addTwo shows the method case. It has the same two overload signatures above one method body. A call with 2 came back as type number, and a call with '2' came back as type string.
This is that class method, as checked with TypeScript 7.0.2.
class Adder {
addTwo(baseNumber: string): string;
addTwo(baseNumber: number): number;
addTwo(baseNumber: string | number) {
const numericTotal = Number(baseNumber) + 2;
return typeof baseNumber === 'string' ? String(numericTotal) : numericTotal;
}
}Constructors take overloads too. The handbook's Classes chapter says "You can add parameters with type annotations, default values, and overloads". Its Point class can be created from (x: number, y: number) or from (xy: string). Those are two overload signatures, and the implementation signature, (x: string | number, y: number = 0), opens the body. The chapter also lists how constructors differ from functions: "Constructors can't have type parameters" and "Constructors can't have return type annotations".
When do optional parameters replace extra overloads?#
Optional parameters replace extra overloads when the overloads differ just in their trailing function parameters and share one return type. The handbook's Do's and Don'ts page says "Don't write several overloads that differ only in trailing parameters". Its fix for diff is one signature, diff(one: string, two?: string, three?: boolean): number. The two overloads of addTwo do not fit that fix. They take the same number of arguments and return different types, a string and a number.
What does the TypeScript handbook say about overload signatures?#
The TypeScript handbook's More on Functions chapter says "The signature of the implementation is not visible from the outside", so callers see only the overload signatures. It also says "you should always have two or more signatures above the implementation of the function". It adds "TypeScript can only resolve a function call to a single overload". TypeScript's Do's and Don'ts page says "TypeScript chooses the first matching overload when resolving function calls". The post calls overloading "giving a function more than one function signature".
| Rule | The handbook's words |
|---|---|
| Callers see | "The signature of the implementation is not visible from the outside". |
| How many | "When writing an overloaded function, you should always have two or more signatures above the implementation of the function". |
| One per call | "TypeScript can only resolve a function call to a single overload" |
| Which one wins | "TypeScript chooses the first matching overload when resolving function calls". |
| Trailing parameters | "Do use optional parameters whenever possible" |
Overloads can differ in how many arguments they take. The handbook's makeDate example writes "two overloads: one accepting one argument, and another accepting three arguments". Its implementation has two optional parameters after the required one. Even so, the handbook notes that it "can't be called with two parameters".
The overloaded addTwo earlier in this post meets the "two or more" rule. It puts one signature for string and one for number above its implementation.
The last two rows come from TypeScript's Do's and Don'ts page. It explains why order matters: "When an earlier overload is 'more general' than a later one, the later one is effectively hidden and cannot be called". Its advice is to put "the more general signatures after more specific signatures". On trailing parameters it adds a limit: "this collapsing should only occur when all overloads have the same return type".
What do Parameters and ReturnType return for an overloaded function?#
The post says "The first two changes are the overloads, which spell out the consequences of using one type versus the other". Parameters and ReturnType read only one of those overloads: the last signature. The last overload of addTwo takes a number and returns a number. So the two types give [baseNumber: number] and number, and the string case does not appear.
The TypeScript Utility Types reference states the rule under each type. It says Parameters "Constructs a tuple type from the types used in the parameters of a function type Type". It says ReturnType "Constructs a type consisting of the return type of function Type". Each entry then adds a line for overloaded functions.
| Utility type | What the reference says | Result for addTwo |
|---|---|---|
| ReturnType | "For overloaded functions, this will be the return type of the last signature" | number |
| Parameters | "For overloaded functions, this will be the parameters of the last signature" | [baseNumber: number] |
The handbook's Conditional Types chapter gives the reason. It says "inferences are made from the last signature (which, presumably, is the most permissive catch-all case)". It adds: "It is not possible to perform overload resolution based on a list of argument types".
The handbook's own example ends with that catch-all case. This code is copied from the Conditional Types chapter.
declare function stringOrNum(x: string): number;
declare function stringOrNum(x: number): string;
declare function stringOrNum(x: string | number): string | number;
type T1 = ReturnType<typeof stringOrNum>;The handbook shows T1 as string | number. That union is the return type of the third and last signature. So the order of the signatures decides what ReturnType reports.
Why does a value that could be either type fail an overloaded call?#
A value typed as a string or a number fails an overloaded call when no single overload accepts both types. The handbook's reason is that "TypeScript can only resolve a function call to a single overload". The post's rule, "if it's a string coming in, it's a string coming out," names one known case at a time. A value that might be either type is a third case.
The handbook's Writing Good Overloads section shows this with a len function. It has one overload for a string and one for an array. Calling it with a value that might be either gives the error "No overload matches this call".
The handbook's Conditional Types chapter has a createLabel example that writes three overloads, ending with a catch-all:
- One overload per known type. The handbook writes "one for each case when we're sure of the type (one for string and one for number)".
- One catch-all. It adds "one for the most general case (taking a string | number)".
- The catch-all last. The ordering rule above puts "the more general signatures after more specific signatures".
A catch-all placed last also changes what the utility types report. As the stringOrNum example above shows, ReturnType then gives the catch-all's union.
When is a union type or a conditional type a better fit than overloads?#
A union parameter fits when the overloads have "the same argument count and same return type", which is why the handbook's More on Functions chapter swaps two overloads for one union parameter. A conditional type fits when the overloads multiply. The handbook's Conditional Types chapter warns that "For every new type createLabel can handle, the number of overloads grows exponentially". That chapter says a conditional type can "describe the relation between the types of inputs and outputs". The two overloads of addTwo return different types, string and number, so the union rule does not fit it.
| Approach | What the handbook says |
|---|---|
| Union parameter | "Always prefer parameters with union types instead of overloads when possible" |
| Overloads | "For every new type createLabel can handle, the number of overloads grows exponentially". |
| Conditional type | "We can then use that conditional type to simplify our overloads down to a single function with no overloads". |
The Gnar Company continues this series in Figurative Literals: Sharpen your Strings. That post keeps both overloads and replaces string in the first one with a template literal type, NumberString. It sums up the change: "We've just moved an error report from run-time to compile-time (or dev time, if our editor is Typescript-aware)".
[1] This section is true as of Typescript 4.5.4.
Learn more about how The Gnar builds software.


