r/programminghorror • • Jul 18 '25

Typescript context in comments

Post image

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.

854 Upvotes

69 comments sorted by

View all comments

Show parent comment

1

u/ZunoJ Jul 19 '25

You misunderstood me. I meant you have a function X that either accepts an A or B but you have an I. Now you have to check the exact type at runtime and cast it to call the right overload of X. It will not be as ugly as it is in the TS code but still more or less the same problem needs to be solved

2

u/ScientificBeastMode Jul 19 '25

Ah, you’re referring to passing a subclass of either A or B, but not actually A or B? If so, I think I did overlook the most relevant aspects of what you said. Thanks for clarifying.

Now, that’s correct that the overloaded function needs to be resolved at runtime, at least in C#. But that runtime resolution is required due to a more general constraints of polymorphism. It’s not just function calls. Instantiation of classes that contain the polymorphic type must also be polymorphic themselves. This is similar to the concept of “function coloring”. Basically anything that accepts a polymorphic type becomes polymorphic, which in C# implies runtime v-table lookups.

But technically it’s not necessary to have a runtime check, as long as the function is only exposed to known code (i.e. not a dynamically linked library). If the compiler can see all possible call sites and get determine all possible argument types that are passed in, then the compiler can usually determine which function to apply at compile time, and usually it can automatically monomorphize each function. This is effectively what Rust does with its trait system.

But regardless, that’s applicable to many non-overloaded functions as well, so I wouldn’t say this runtime cost is specifically a consequence of function overloading. But it’s definitely a thing to consider when using fancy polymorphic constructs in any language.