简体   繁体   中英

Getting Typescript strictNullChecks to work with undefined returning vanilla js functions

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM