简体   繁体   中英

How can object be null/undefined after checking that object property is an integer using Number.isInteger?

Here is my code:

if (
  Number.isInteger(prevObj?.prop) &&
  Number.isInteger(nextObj?.prop) &&
  prevObj.prop !== nextObj.prop
) {
...
}

TypeScript is warning that prevObj / nextObj could be null or undefined after checking that prop is an integer.

If i use typeof prevObj?.prop === 'number' instead of Number.isInteger , the warnings go away.

Can you explain why TypeScript is showing these warnings?

TypeScript is showing these warnings because the type checker doesn't know that prevObj and nextObj are defined when you use the optional chaining operator (?). When you use optional chaining, the type checker considers the type of the property to be a union of the actual type and undefined, so it doesn't know that the property is definitely an integer.

You can fix the issue by either using typeof to check the type of the property, as you mentioned, or by providing a type assertion to tell the type checker that the object is definitely defined:


    if (
          Number.isInteger((prevObj as { prop: number }).prop) &&
          Number.isInteger((nextObj as { prop: number }).prop) &&
          prevObj.prop !== nextObj.prop
        ) {
          // ...
    }

This will tell the type checker that prevObj and nextObj are definitely defined and have a property prop of type number, so it won't show the warning.

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