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"}