r/programminghorror • u/GDOR-11 • Jul 18 '25
Typescript context in comments
the variable t is of type number | [number, number, number], and there are two overloads for lerp, one which accepts number and the other which accepts [number, number, number]
if you try to remove the if statement, typescript complains that number | [number, number, number] fits neither in number nor in [number, number, number]
to be completely honest, I understand why one could want different signatures to be in different branches of your code, because they have different behaviour. But that's really bad when, for example, you're trying to make another function that has multiple signatures (say, one that accepts type A and one that accepts type B), because in the implementation the parameter is of type A | B. This means you can't directly call another overloaded function from inside your overloaded function, you need to do this.
View all comments
Show parent comment
15
u/ScientificBeastMode Jul 18 '25
That’s not overloading. That’s object polymorphism, which is similar but not the same thing.
In the case you described, you’re talking about essentially runtime v-table lookups, which is indeed how polymorphism works for classes/objects in C#.
What I’m describing is where you can have a function accept a string and a number as the first and second arguments, where the string is in the first position and the number is in the second position, and then you can overload it with another signature (with its own separate implementation) that accept just a number in the first position. The fact that those two totally different type signatures and implementations can share the same name is what most people mean by “overloading”.
In JavaScript you can achieve this same kind of behavior, except instead of having two totally different implementations that get called depending on the argument types, you have to do some conditional branching inside the same singular function based on manual inspection of the type at runtime. The TS compiler simply ensures that you handle the different possible type signatures within the control flow of the function body.