3 ms·
Type 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 devel
by MrJohz 4y ago
Type 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.