[英]Typescript not inferring correct type after type check inside a ternary operator
我有这个组件,它接受一个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
};
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
但是,建议使用猫王运算符“?”。 但在您的情况下,由于“-1”操作,这是不可能的。 所以你必须再次测试 props.error:
在你的情况下:
marginBottom={props.error && index === props.error.length -1 ? "0px" : "8px"}
在可能具有不同类型的数组上使用map()
时,我遇到了类似的错误。 您检查了 null 并检查了一个数组,因此当这些检查通过时,您可以确定您的错误道具是一个字符串数组,您可以执行以下操作:
(props.error as string[]).map((item,index)
或者您可以直接在简写 if 语句中的props.error
上使用string[]
marginBottom={index === (props.error as string[]).length -1 ? "0px" : "8px"}
添加额外的空检查:
marginBottom={props.error && index === props.error.length -1 ? "0px" : "8px"}
使用! operator
! operator
将此属性定义为非空:
marginBottom={index === props.error!.length -1 ? "0px" : "8px"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.