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