Hacker News new | past | comments | ask | show | jobs | submit login

That runs counter to one of the goals of TypeScript, which is to make no runtime changes.

It’s easy enough to do this in userland. I wrote a tiny library called narrows which has worked great for me: https://www.npmjs.com/package/narrows




When I read your comment I had high expectations about narrows.

After I looked at it, I have a sour feeling in my mouth. Why there can't be a way (or a library) to do very easy type guards in TypeScript? Something as simple as the keyword `is` in C#


It’s for the reason I mentioned before: one of TypeScript’s primary goals is that it generates no runtime code. If you run the TypeScript compiler, it will generate exactly the same JavaScript code with the types removed*. Since there is no such JavaScript feature, there will be no such TypeScript feature.

I’ll add that writing manual type guards is fairly infrequent, so in practice there’s not a lot to gain here.

*Modulo polyfilling newer ES features if you compile for a lower version of the spec.


Presumably because of type erasure during compilation. If you had access to a runtime representation of a TS type you could do something like that.


Cool library, the type guards look interesting. Too bad it's not more automatic but yeah it's not very much extra code




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

Search: