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
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#
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.
That you can do something so sophisticated is a testament to TypeScript's type system.
However, if you were writing JavaScript, I think it's (unfortunately) uncommon to have this kind of proactive validation. So, for people writing TypeScript as "JavaScript + types" (which is a perfectly fine way to use it), they would just use a type assertion, which is just writing down the assumption that the JavaScript programmer makes when consuming but not validating external data.
https://2ality.com/2020/06/validating-data-typescript.html#p...