With idiomatic js returning undefined on error, converted to TS
function multiply(foo: number | undefined){
if (typeof foo !== "number"){
return;
};
return 5 * foo;
}
When using multiply in new TS code i get the problem of the compiler believing doStuff can return undefined, when it cannot.
So i tried to write an "unsafe" version of this function called by safe TS code, leaving the safe version for regular js code.
function unsafeMultiply(num: number){
return multiply(num);
}
Since unsafeMultiply can only accept a number, the type guard in multiply should consider that multiply will only return a number since unsafeMultiply can only process number. If this is too complicated for the compiler, how do i force him to accept i know what i'm doing ?
Yes, it can:
multiply(undefined)returnsundefined.You can do a type assertion, since you know that
multiplywill only returnundefinedif it is called with a non-number:Or you can add code for a type guard at runtime:
But if it were me, I'd make the
multiplyfunction fail or returnNaNrather than returningundefined, if givenundefined. ThenunsafeMultiplywouldn't be needed.