简体   繁体   English

“对象可能是'未定义的'”在reactjs中使用typescript

[英]“Object is possibly 'undefined'” in reactjs with typescript

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: 我第一次在反应proj中使用typescript,我遇到了错误:

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): 这是我的代码(在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: 这是界面,我已将questions属性声明为可选:

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. TypeScript抱怨的原因是因为它很难检测到你之前已经进行了空检查。 One way to tell TS that you are certain that the property will exist is using non-null assertion operator (!): 告诉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>
      </>
   )}

   ...
)

or you could also do what others suggested and replicate the null check: 或者你也可以做别人的建议并复制空检查:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM