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

14,916

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>;
            })}
Share:
14,916
Wendigo
Author by

Wendigo

Hello there, I'm Gabriele, a Software Engineer.

Updated on June 09, 2022

Comments

  • Wendigo
    Wendigo almost 2 years

    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?