Getting Typescript strictNullChecks to work with undefined returning vanilla js functions

204 Views Asked by At

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 ?

1

There are 1 best solutions below

4
T.J. Crowder On BEST ANSWER

When using multiply in new TS code i get the problem of the compiler believing doStuff can return undefined, when it cannot.

Yes, it can: multiply(undefined) returns undefined.

If this is too complicated for the compiler, how do i force him to accept i know what i'm doing ?

You can do a type assertion, since you know that multiply will only return undefined if it is called with a non-number:

function unsafeMultiply(num: number) {
   return multiply(num) as number;
}

Or you can add code for a type guard at runtime:

function unsafeMultiply(num: number) {
  let result = multiply(num);
  if (typeof result === "undefined") {
    throw new Error("Invalid num argument");
  }
  return result;
}

But if it were me, I'd make the multiply function fail or return NaN rather than returning undefined, if given undefined. Then unsafeMultiply wouldn't be needed.