我已经搜索了一段时间,在网上发现了类似的问题,但似乎没有一个解决方案适合我。
我第一次在我的 react 项目中使用 typescript ,我遇到了一个错误:Object is possibly 'undefined'
我一直在想办法解决这个问题,但到目前为止还没有找到任何解决方案。
这是我的代码(在 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>
</>
)}
...
)
这是接口(interface),我在这里声明了
questions
可选属性:interface Question {
...
options?: string[];
...
}
我怎么可能解决这个问题?
最佳答案
TypeScript 提示的原因是它很难检测到您之前已经进行了空检查。告诉 TS 您确定该属性将存在的一种方法是使用非空断言运算符 (!):
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>
</>
)}
...
)
或者您也可以执行其他人的建议并复制空检查:
{questions[currentStep].options && questions[currentStep].options!.map(question => {
<option>{question}</option>;
})}
关于javascript - "Object is possibly ' 在带有 typescript 的 reactjs 中未定义 '",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55900443/