Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Object is possibly 'undefined'" in reactjs with typescript

I've been searching for a while, and found similiar problems on the web, but none of the solutions seems to work for me.

I'm using typescript in my react proj for the very first time, and I'm having an error:

Object is possibly 'undefined'

I've been trying to figure out how to fix this, but haven't found any solutions so far.

Here's my code (inside a functional component in reactjs):

return(
   ...

   {questions[currentStep].type === 'select' && 
   questions[currentStep].options && (
      <>
         <select id="question" onChange={submitForm} autoFocus required>
            <option value="" />

            {questions[currentStep].options.map(question => {
               <option>{question}</option>;
            })}
         </select>
         <label htmlFor="question">{questions[currentStep].text}}</label>
      </>
   )}

   ...
)

And this is the interface, where i've declared the questions attribute as optional:

interface Question {
  ...
  options?: string[];
  ...
}

How can I possibly fix this problem?

like image 219
Wendigo Avatar asked Nov 30 '22 13:11

Wendigo


1 Answers

The reason TypeScript complains is because it struggles to detect that you've already made a null check prior. One way to tell TS that you are certain that the property will exist is using non-null assertion operator (!):

return(
   ...

   {questions[currentStep].type === 'select' && 
   questions[currentStep].options && (
      <>
         <select id="question" onChange={submitForm} autoFocus required>
            <option value="" />

            {questions[currentStep].options!.map(question => {
               <option>{question}</option>;
            })}
         </select>
         <label htmlFor="question">{questions[currentStep].text}}</label>
      </>
   )}

   ...
)

or you could also do what others suggested and replicate the null check:

{questions[currentStep].options && questions[currentStep].options!.map(question => {
               <option>{question}</option>;
            })}
like image 108
Vasil Dininski Avatar answered Dec 04 '22 06:12

Vasil Dininski