3 ms·
I still don't get it. Please help me out. Why should the type system have anything to do with something like this? function something(num : number) { as
by deepersprout 7y ago
I still don't get it. Please help me out.
Why should the type system have anything to do with something like this?
function something(num : number) {
assertIsInRange(num);
return num + 1;
}
function assertIsInRange(num: number, msg?: string): asserts num {
if (num < 50 || num > 100) {
throw new Error('not in range');
}
}
something(50);
How is `asserts num` helping here?
- mceachen 7y agoIf your something function was `something (num: string|number)`, typescript can safely trust that`num` is a number in the block proceeded by your call to assert because it knows it must be a number, not a string.
- jiofih 7y agoThis, and undefined values. Will be of huge value for dealing with protobuf data, where all keys are optional.
- deepersprout 7y agoIf the `something` function had `(num: string | number)` I would not be able to call `assertIsInRange(num: number)` because `Argument of type 'string | number' is not assignable to parameter of type 'number'.` So If I wanted to do that I would have to if (typeof num === 'number') { assertIsInRange(num); } anyway. I think I still don't get it.
- bsaul 7y agoi’m not sure about typescript, but in many languages assertion have the natural behavior of being compiled out of release builds and kept only for debug mode. The fact that it’s a built in feature of the language also can sometimes helps the compiler infer what’s the properties of code after it. But theoretically , yes you could very well code some equivalent testing function yourself, except for the compiler inference part it would probably be equivalent.
- deepersprout 7y ago> i’m not sure about typescript, but in many languages assertion have the natural behavior of being compiled out of release builds and kept only for debug mode. Not in TS. This code function something(num : number) { assertIsInRange(num); return num + 1; } function assertIsInRange(num: number, msg?: string): asserts num { if (num < 50 || num > 100) { throw new Error('not in range'); } } something(50); gets compiled to function something(num) { assertIsInRange(num); return num + 1; } function assertIsInRange(num, msg) { if (num < 50 || num > 100) { throw new Error('not in range'); } } something(50);