为什么 Typescript 在数组长度检查上用大于但不等于标记可能的未定义值?



给定 React 组件的这个片段:

const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => {
const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : true
...

为什么 Typescript 抱怨当我检查它是否大于 0 时props.accountData?.customerAccounts?.length可能未定义(> 0)但当我检查它是否等于 1(=== 1)时错误消失了?

这是JS正在做一些奇怪的事情,未定义的属性被解释为0的情况吗?

以这种方式编写它消除了错误,但我正在尝试理解这种行为。

const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length ?? 0 > 1 ? : true : false

更简单地说,你问为什么TypeScript抱怨这些语句中的第二个:

console.log(undefined === 1);   // false
console.log(undefined > 0);
//          ^−−−− Object is possibly 'undefined'.(2532)

。因为任何具有可选链接的属性访问操作都必须undefined为其可能的结果值之一。

===>更笼统。===用于查看操作数的值类型是否匹配。但是>用于比较两个数字或比较两个字符串的相对"更大"性。TypeScript 还可以防止将这两者混合:

console.log("1" > 0);
//          ^−−− Operator '>' cannot be applied to types 'string' and 'number'.(2365)
console.log(1 > "0"");
//          ^−−− Operator '>' cannot be applied to types 'number' and 'string'.(2365)

在 JavaScript 中,我们(相当)习惯于在这些情况下进行隐式转换,但 TypeScript 的工作是应用严格的类型,因此通常不允许隐式转换。在 JavaScript 中,undefined > 0变得NaN > 0false(就像undefined <= 0一样)。但是TypeScript认为这可能是错误,并为您标记它。

(以上所有内容的游乐场链接。

如果你想使用length > 0你需要空合并:

const i: number | undefined = undefined;
if (i ?? 0 > 0) {
}

最新更新