Hacker News new | ask | show | jobs
by iainmerrick 1373 days ago
I think that’s actually a positive feature of TypeScript -- a useful limitation. Reflection is generally a bad idea and it’s good to be forced to do without it.

It is a bit annoying sometimes that you can’t have overloaded functions with different types, but in that case you can usually just give the overloads different names, and usually that’s better for readability anyway. (Or if you really want to, write one function and use JS reflection to do the overloading manually) (but you really don’t!)

Here’s an interesting discussion of the overloading question in Swift: https://belkadan.com/blog/2021/08/Swift-Regret-Type-based-Ov...

3 comments

> Reflection is generally a bad idea

it is not - dynamic reflection certainly has its issues, but static reflection is absolutely fine

> it’s good to be forced to do without it.

it just leads to people reinventing it even more badly with separate tools

You’re right, I was just thinking about dynamic reflection.

My concern is with fiddly runtime stuff like “instanceof” -- I find that can go wrong in surprising ways. Better to just trust values to implement the interface they say they implement rather than trying to forcibly cast them.

Wanted to note that you can do function signature overloading in typescript- you just have to have a single function at the bottom that encapsulates all the different signatures and then branches its logic dynamically based on the values it's given: https://stackoverflow.com/questions/13212625/typescript-func...

I actually think this is a super cool and elegant way to do overloading

How do you give the overloads different names? Can you give a little example?
I’m just thinking of separate functions like this, which you can do in many languages:

add(n: number)

add(s: string)

In TypeScript (and also in C and Objective-C) you need to give them different names:

addNumber(n: number)

addString(s: string)

But see also brundolf’s reply -- if you have a single function that happens to take multiple overloads, TS does let you declare each overload; but it still needs a single implementation (likely with some runtime dispatching) in that case. I haven’t used that much myself, but maybe I should give it a go!