5 ms·
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 calle
by jakelazaroff 6y ago
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 https://www.npmjs.com/package/narrows
- ivan888 6y agoCool library, the type guards look interesting. Too bad it's not more automatic but yeah it's not very much extra code
- knocte 6y agoWhen 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#
- jakelazaroff 6y agoIt’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.
- giantDinosaur 6y agoPresumably because of type erasure during compilation. If you had access to a runtime representation of a TS type you could do something like that.