Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Typescript does not infer union types for return types. You can explicitly annotate them just fine though.

I suppose the reasoning is that, when adding types to js, this is exactly the kind of bad behaviour you want to catch. But I'm not sure, perhaps there are just technical implications for not inferring union return types.



Exactly. Leaving off the return type annotation is just asking for trouble, and this example proves it.

And the actual type of the const won't be `string | number` -- it will be `any`.

MaulingMonkey[1] has the right idea, though.

[1] https://news.ycombinator.com/item?id=12192240




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: