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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With