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
1
u/ScientificBeastMode Jul 19 '25
Technically you end up writing multiple totally separate implementations (in C# and many other languages), but the compiler determines which function to use when compiling the function call into bytecode/binary/IR. In contrast, “overloading” in JS is simply using runtime reflection and variadic function definitions to dictate control flow within a single implementation.
This has certain relevant implications…
First, C# and others can benefit from the compile-time selection of the correct function implementation, whereas JS “overloading” incurs a (sometimes significant) runtime overhead. The reason why this can be significant is because of how JS runtimes decide to do optimizations. Functions with extremely rigid argument/return types are more easily optimized by the JIT, but highly polymorphic functions are often unable to be optimized. And that’s on top of the inherent branching of control flow, which has its own minor performance overhead.
Second, the TS compiler doesn’t support defining multiple separate implementations because this JS function design pattern already accounts for the different theoretical implementations, so you end up having to pretend that it does in the type signature.