4 ms·
Good list, but type guards are just as unsafe as type assertions. I wrote a blog post about this: https://fnune.com/typescript/2019/02/27/typescript-series-2-be
by brainlessdev 6y ago
Good list, but type guards are just as unsafe as type assertions. I wrote a blog post about this: https://fnune.com/typescript/2019/02/27/typescript-series-2-beware-the-type-guards/ https://fnune.com/typescript/2019/02/27/typescript-series-2-...
TypeScript will believe what you tell it in a type guard's signature without looking at the body of the function further than "does it return a boolean".
- SamBam 6y agoTypeScript 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.
- g_delgado14 6y agoI think their point is simply that type guards aren't a panacea.
- xmprt 6y agoWhat'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).
- Aeolun 6y agoYou can use guards for things other than primitive types.
- SamBam 6y agoA 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.
- brainlessdev 6y agoI 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.