Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在三元运算符内进行类型检查后,Typescript未推断正确的类型_Javascript_Reactjs_Typescript_Type Inference - Fatal编程技术网

Javascript 在三元运算符内进行类型检查后,Typescript未推断正确的类型

Javascript 在三元运算符内进行类型检查后,Typescript未推断正确的类型,javascript,reactjs,typescript,type-inference,Javascript,Reactjs,Typescript,Type Inference,我有一个组件,它接受一个错误属性,该属性可能是null、string或string[] interface ErrorComponent { error: null | string | string[] // props.error UNION TYPES } const ErrorComponent: React.FC<ErrorComponent> = (props) => { const errorItems = props.error ?

我有一个组件,它接受一个
错误
属性,该属性可能是
null
string
string[]


interface ErrorComponent {
  error: null | string | string[]      // props.error UNION TYPES
}

const ErrorComponent: React.FC<ErrorComponent> = (props) => {

  const errorItems = props.error ?               // CHECK IF props.error EXISTS (string | string[])
    Array.isArray(props.error) ?                 // CEHCK IF props.error IS AN ARRAY
      props.error.map((item,index) =>            // CASE string[]
        <Error_DIV 
          key={index} 
          marginBottom={index === props.error.length -1 ? "0px" : "8px"}   // GETTING WARNING FOR POSSIBLE null HERE
        >
          {item}
        </Error_DIV>
      )
    : <Error_DIV>{props.error}</Error_DIV>       // CASE string
  : null;                                        // CASE null

  // return SOMETHING
};


接口错误组件{
错误:null | string | string[]//props.error联合类型
}
常量错误组件:React.FC=(道具)=>{
const errorItems=props.error?//检查props.error是否存在(字符串|字符串[])
Array.isArray(props.error)//CEHCK如果props.error是数组
props.error.map((项,索引)=>//大小写字符串[]
{item}
)
:{props.error}//大小写字符串
:null;//大小写为null
//归还某物
};

Typescript正在抱怨
props.error
可能是
null
。但此时,我已经检查了Array.isArray(props.error)。因此,
props.error
不可能是
null


如何修复此问题?

此TSLint规则似乎不太支持JSX:

props.error.map((item,index) => 
    <Error_DIV // Here TSLINT context seems to be reset

在可能具有不同类型的数组上使用
map()
时,我遇到了类似的错误。您检查了null和数组,因此当通过这些检查时,您可以确保错误道具是字符串数组,您可以执行如下操作:

(props.error as string[]).map((item,index)
或者您可以直接在速记if语句中的
props.error
上使用
字符串[]

marginBottom={index === (props.error as string[]).length -1 ? "0px" : "8px"}
添加额外的空检查:

marginBottom={props.error && index === props.error.length -1 ? "0px" : "8px"}
使用
!运算符
将此属性定义为非空:

marginBottom={index === props.error!.length -1 ? "0px" : "8px"}

谢谢当我在
props.error?.length中添加
时,我得到的对象可能是“未定义的”。对,这是因为“-1”。我已经更新了我的答案
marginBottom={index === props.error!.length -1 ? "0px" : "8px"}