Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  76] [ 1]  / answers: 1 / hits: 28567  / 5 Years ago, mon, april 29, 2019, 12:00:00

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?


More From » reactjs

 Answers
95

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>;
})}

[#52178] Monday, April 22, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reina

Total Points: 241
Total Questions: 82
Total Answers: 94

Location: New Caledonia
Member since Thu, Mar 23, 2023
1 Year ago
;