Hacker News new | ask | show | jobs
by shortercode 1752 days ago
As someone who spends a lot of time looking at ASTs it feels slightly naive to write off type keys completely. They are particularly useful in TS because it uses flow analysis to isolate the correct interface pattern from a union of types. Although I will generally encourage using conditional flow to direct to variant specific functions instead of mixing types in the function body.

I would heartily support the refractors given in the examples if they reached me in an MR. But chances are that a type key is introduced in 1 location, and then acted on in 6 different locations with a large temporal distance. Without the type key you are likely to need some way to infer the type, which may be error prone and hard to maintain.

On a micro scale a common example is where you have to pass over a list of statements to declare the functions, and a second time to define them. So that they can be self referential. Preferably without N scale memory allocations caused by things such as filtering the list.

1 comments

My first thought was ASTs and union narrowing too! Probably because that’s been an area of focus for me lately too. Of course there’s other ways to represent a discriminated union, but type keys are particularly useful and usable for AST tools which are designed to be extensible (unified, estree come to mind).

One significant downside, which I think would better support the article’s point, is that type keys make composition (or inheritance if that’s your thing) more awkward. To represent an intersection type, you need either a nested structure (more flexible) or implicit relationships between types (please do not).