Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 636
Caleb Robinson Avatar asked Feb 02 '21 21:02

Caleb Robinson


1 Answers

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

like image 72
jcalz Avatar answered Oct 16 '22 19:10

jcalz