4 ms·
Type guards in TypeScript are not sound: the language makes no effort to prevent you from defining an incorrect type guard that, when used, narrows your variabl
by anderskaseorg 4y ago
Type guards in TypeScript are not sound: the language makes no effort to prevent you from defining an incorrect type guard that, when used, narrows your variables to incorrect types. Your mistake won’t be caught at compile or at runtime (until the variable is actually used in a way that’s incompatible with its declared type, which may be much later).
- MrJohz 4y agoType guards (X is number) are different from type assertions (X as number). The former are user defined runtime checks - if they are not correct, then the developer who wrote them is at fault. Moreover, they are typechecked, so you couldn't have a type guard that claims to return a number but actually returns an array, at least not without bypassing the Typescript checker some other way. Type assertions match what you describe better - they are ways to override the compiler's opinion about the type of a variable or expression. They are, as you say, unsafe in the sense that the compiler has no way of knowing if this assertion is true or not.
- matt_kantor 4y ago> they are typechecked, so you couldn't have a type guard that claims to return a number but actually returns an array, at least not without bypassing the Typescript checker some other way Sadly this isn't true: https://tsplay.dev/WvGArw https://tsplay.dev/WvGArw
- MrJohz 4y agoGood point, I wasn't 100% sure on that and should have checked myself. I'd say there's still a lot of value in having type guards as explicit places that can be heavily checked, e.g. with unit tests, to form strong boundaries to the rest of the code you right.