TypeScript:内联空检查混淆,在特定用法下不起作用

TypeScript: inline null check confusion, not working in particular usage

这是一段 TypeScript 代码:

if (props.categories && props.categories.length > 0) {
  // code...
}

props.categories 定义如下:

interface MyComponentProps {
  categories?: string[];
}

我对这里的 ? 运算符有点困惑...我认为我可以将条件缩短为:

if (props.categories?.length > 0) {
  // code...
}

但是,TypeScript 抱怨说“对象可能未定义”。这是为什么?

props.categories?.length > 0 可能会决定 undefined > 0 这是错误的根源。 所以,它与 props.categories && props.categories.length > 0.

并不严格相同

我的建议是保持原样。如果你真的真的想在这里使用可选的链接运算符,你可能只需要默认一个数字来比较

props.categories?.length ?? 0 > 0

但是,这也好不到哪儿去。