In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem.
function multiply(foo: number | undefined){
if (typeof foo !== "number"){
return;
};
return 5 * foo;
}
When trying to use the `multiply` function in my new TypeScript code, the compiler is assuming that it can return undefined, even though it cannot do so.
To work around this issue, I created an "unsafe" version of the `multiply` function which will only be called by safe TypeScript code, leaving the regular JavaScript code to use the original safe version.
function unsafeMultiply(num: number){
return multiply(num);
}
Since `unsafeMultiply` only accepts numbers as input, the type guard in `multiply` should recognize that it will only ever return a number since `unsafeMultiply` can only process numbers. If this concept is too complex for the TypeScript compiler, how can I convince it that I know what I'm doing?