简体   繁体   English

在使用 Number.isInteger 检查 object 属性是 integer 后,object 怎么可能为 null/undefined?

[英]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. TypeScript 警告prevObj / nextObj可能是null或在检查prop是 integerundefined

If i use typeof prevObj?.prop === 'number' instead of Number.isInteger , the warnings go away.如果我使用typeof prevObj?.prop === 'number'而不是Number.isInteger ,警告 go 就会消失。

Can you explain why TypeScript is showing these warnings?您能解释一下为什么 TypeScript 会显示这些警告吗?

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 (?). TypeScript 显示这些警告是因为类型检查器不知道在您使用可选链接运算符 (?) 时定义了 prevObj 和 nextObj。 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.当您使用可选链接时,类型检查器认为属性的类型是实际类型和未定义的联合,因此它不知道该属性肯定是 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:您可以通过使用 typeof 检查属性的类型来解决此问题,正如您提到的那样,或者通过提供类型断言来告诉类型检查器 object 已明确定义:


    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.这将告诉类型检查器 prevObj 和 nextObj 已明确定义并且具有类型为 number 的属性 prop,因此它不会显示警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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