简体   繁体   中英

Object is possibly 'undefined' Error on Optional Chaining Typescript

I have a response which I am accessing: data?.currentOrganization?.onboardingSteps? . As you can guess, data, currentOrganization, and onboardingSteps might all be 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. However, I get the TypeScript error: 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. You can't test undefined > 0 without Typescript complaining about it.

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 .

Playground link to code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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