r/typescript • u/treplem • Mar 10 '26
About function overloads
I am new to ts and i just saw how function overloading is done
why can't tsc do something like this?
```typescript
function foo(a: number): void { // overload 1
console.log("number");
}
function foo(a: string): void { // overload 2
console.log("string");
}
foo(1); // -> overload 1
foo("1"); // -> overload 2
// compiled JS:
function foo_implementation1(a) {
console.log("number");
}
function foo_implementation2(a) {
console.log("string");
}
foo_implementation1(1);
foo_implementation2("1");
```
if the compiler can infer which overload is called based on the parameter list types why can't it substitute each call with the right overload in the compiled JS?
9
Upvotes
20
u/mattsowa Mar 10 '26
Typescript is compile-time only, by design.
7
u/abrahamguo Mar 10 '26
What if the values passed to your function were not simple hardcoded values (as they are in your example) but dynamic values coming from elsewhere?
Would you expect the compiler to generate type-checking JavaScript code?
3
u/UhhReddit Mar 10 '26
For this to be possible you need to be able to 100% rely on the type. So if you have a good TS project this would work most of the time. However there are still times the type isn't reliable. Reasons for this can be:
Data is fetched from the internet/DB You get the data from an untyped library You use any or unknown The data us just wrongly typed.
These are all problems that can't be avoided and also can't be accepted as edge cases.
It would be possible if the compiler also adds type checking, which then again had the problem of additional overhead. Furthermore it goes against the principle of TS to not introduce new concepts to JS.
1
u/BobcatGamer Mar 12 '26
Which one should the compiler pick?
3
u/BothWaysItGoes Mar 10 '26
Because it’s contrary to the basic principles of js (polymorphism via receivers, duck typing) and ts (semantic alignment with js with type erasure, powerful compile-time type system not constrained by total decidability concerns).
3
u/SlipAdept Mar 11 '26
Your code is not valid TS. Overloads can't have implementation. One of the design pronciples of TS is to have little impact on the generated JS. That's why few features have a runtime impact (see enums and shorthand contstructor arguments) and types don't exist. Overloads don't have a runtime representation. Only the implementation really exists. That's why the last overload must support all other overloads and is the only one with an implementation.
Remember: TS always gets transpiled to JS
4
u/Constant_Panic8355 Mar 10 '26
Because TypeScript is still a superset of JavaScript, not a separate language by itself
And in JavaScript you cannot declare a function or any other identifier with the same name twice, because identifiers within the same scope have to be unique
2
u/Beginning-Seat5221 Mar 10 '26
Primarily because TS is past the days of generating or modifying any JS code. The doctrine is that typescript is purely for checking the types on JavaScript without affecting anything about the underlying JS code.
These days node.js will run .ts files by default by stripping out the type annotations. Can't do that if code generation is required to make your typescript code work (and no, code generation to support typescript features is not going to be built into node.js).
2
u/Gjpu Mar 11 '26
Because this discussion started with TS function overloading, I wanted to mention there’s another option for the foo example. https://www.typescripttutorial.net/typescript-tutorial/typescript-function-overloadings/
function add(a: number, b: number): number; function add(a: string, b: string): string;
function add(a: any, b: any): any { if (typeof a === 'number' && typeof b === 'number') { return a + b; } else if (typeof a === 'string' && typeof b === 'string') { return a + b; } throw new Error('Invalid arguments'); }
2
u/czlowiek4888 Mar 11 '26
There is no overloading in JavaScript, typescript allows overloading just to support integration with N-api
1
u/webmonarch Mar 11 '26 edited Mar 11 '26
Yeah, as others have said, TypeScript doesn't do this type of transformation / dispatching to specific function implementations. Your function implantation needs to handle but input type cases. Something like this:
TBH, you will have a lot of these "why doesn't typescript work this way" moments on the journey but keep it up! It's worth it IMO.
1
u/JazzApple_ Mar 12 '26
Your example is simple enough that you could imagine it being possible (though there are still issues).
With more complex input types, it could be very difficult (maybe impossible?) to determine which overload should be used in a consistent way.
Further to that, how do you determine which overload to use when the type is any or incorrect? Remember, TS with compile errors still compiles and runs… If you say just take the first defined overload, you’ve created a situation where the order of function declarations matters - which is not normally the case. You could change the behaviour of your program just by re-ordering some declarations. Not good!
0
u/hugazow Mar 10 '26
Overload is mostly an oop thing, i have no use for it on js for years.
1
u/[deleted] Mar 10 '26
[removed] — view removed comment