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

TypeScript can't always save you against yourself. But adding in the TypeGuard makes the intent explicit. If your guard isn't actually verifying the thing has the structure you say, of course it's going to fail. But at that point your code was going to fail anyway (say if you just cast it to the type), with a less-useful error message.

I don't quite understand the criticism. You may as well say that unit tests are just as unsafe as not writing unit tests, because your test might not do what you think it's doing.




What's the difference between failing a type assertion vs failing a type guard? Both fail at runtime, right? So I don't understand how one would be better than another. Type assertions seem pretty explicit to me (saying you want this result to be as a certain type).


A failing type assertion that correctly fails because the input is not that type is good: it lets you divert to another path. E.g. if it's Type X do this, if it's Type Y do that. Or even just put up a vaguely-useful error to the user: "The third-party service didn't send the expected data" instead of throwing the obscure error `Cannot read property 'prop' of responseData` in the console and freezing.


You can use guards for things other than primitive types.


I use type guards as well. It's not criticism: I just stated the fact that you can write incorrect type guards and the compiler will believe you.

I elaborate on ways to use them effectively in the post.


I think their point is simply that type guards aren't a panacea.




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

Search: