对象可能是 'undefined' 可选链接打字稿错误

Object is possibly 'undefined' Error on Optional Chaining Typescript

我正在访问一个回复:data?.currentOrganization?.onboardingSteps?。您可以猜到,data、currentOrganization 和 onboardingSteps 可能都为空。我想分配一个变量如下:

const hasSteps = data?.currentOrganization?.onboardingSteps?.length > 0;

我认为如果任何字段为 null 或少于 1 步,hasValue 将计算为 false。但是,我收到 TypeScript 错误:Object is possibly 'undefined'.

这就是我目前的解决方法:

const hasSteps =
  data?.currentOrganization?.onboardingSteps != null &&
  data?.currentOrganization?.onboardingSteps?.length > 0;

这感觉冗长得没必要。是否有其他更优雅的解决方案?

optional chain 最终会为 data?.currentOrganization?.onboardingSteps?.length 生成一个值,如果链中的所有内容都不是 nullundefined,则可能是 number ....但如果链中的任何内容为空,则输出将是 undefined 本身。如果没有 Typescript 的抱怨,你就无法测试 undefined > 0

因此,您可能应该执行以下操作:

const hasSteps = (data?.currentOrganization?.onboardingSteps?.length ?? 0) > 0;

如果可选链以 undefined 结束,则使用 nullish coalescing 生成 0

Playground link to code