[英]Object is possibly 'undefined' Error on Optional Chaining Typescript
I have a response which I am accessing: data?.currentOrganization?.onboardingSteps?
我有一个正在访问的响应:
data?.currentOrganization?.onboardingSteps?
. . As you can guess, data, currentOrganization, and onboardingSteps might all be null.
如您所料,data、currentOrganization 和 onboardingSteps 可能都是 null。 I want to assign a variable as follows:
我想分配一个变量如下:
const hasSteps = data?.currentOrganization?.onboardingSteps?.length > 0;
I thought hasValue would evaluate to false if any of the fields were null or if there was less than 1 step.如果任何字段为 null 或少于 1 步,我认为 hasValue 将评估为 false。 However, I get the TypeScript error:
Object is possibly 'undefined'
.但是,我收到 TypeScript 错误:
Object is possibly 'undefined'
。
This is how I am currently getting around it:这就是我目前解决它的方式:
const hasSteps =
data?.currentOrganization?.onboardingSteps != null &&
data?.currentOrganization?.onboardingSteps?.length > 0;
This feels unnecessarily verbose.这感觉不必要地冗长。 Is there an alternative, more elegant solution?
有没有其他更优雅的解决方案?
The optional chain will end up producing a value for data?.currentOrganization?.onboardingSteps?.length
which is presumably a number
if everything in the chain is not null
or undefined
.... but if anything in the chain is nullish, then the output will be undefined
itself. 可选链最终将产生一个
data?.currentOrganization?.onboardingSteps?.length
的number
,如果链中的所有内容都不是null
或undefined
.... 但如果链中的任何内容为空,则该值可能是一个数字output 本身将是undefined
的。 You can't test undefined > 0
without Typescript complaining about it.如果没有 Typescript 抱怨,您将无法测试
undefined > 0
。
So you should probably do something like the following:因此,您可能应该执行以下操作:
const hasSteps = (data?.currentOrganization?.onboardingSteps?.length ?? 0) > 0;
This is using nullish coalescing to produce 0
if the optional chain ends in undefined
.如果可选链以
undefined
结尾,则使用无效合并来产生0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.