带有打字稿的reactjs中的“对象可能是'未定义'”

Wen*_*igo 4 javascript typescript reactjs

我已经搜索了一段时间,并在网上发现了类似的问题,但似乎没有一个解决方案对我有用。

我第一次在我的 react proj 中使用 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>
      </>
   )}

   ...
)
Run Code Online (Sandbox Code Playgroud)

这是接口,我已将questions属性声明为可选:

interface Question {
  ...
  options?: string[];
  ...
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Vas*_*ski 16

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

   ...
)
Run Code Online (Sandbox Code Playgroud)

或者您也可以按照其他人的建议进行操作并复制空检查:

{questions[currentStep].options && questions[currentStep].options!.map(question => {
               <option>{question}</option>;
            })}
Run Code Online (Sandbox Code Playgroud)