简体   繁体   English

在三元运算符内进行类型检查后,打字稿未推断出正确的类型

[英]Typescript not inferring correct type after type check inside a ternary operator

I have this component that takes an error prop that might be null , string or string[] .我有这个组件,它接受一个error道具,它可能是nullstringstring[]


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 is complaining that props.error could be null . Typescript 抱怨props.error可能是null But at that point, I've already made the check Array.isArray(props.error) .但那时,我已经进行了检查Array.isArray(props.error) So, there's no way the props.error could be null .所以, props.error不可能是null

How can I fix this?我怎样才能解决这个问题?

It seems that this TSLint rule does not support JSX very well:看来这个 TSLint 规则对 JSX 的支持不是很好:

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

However, it is recommended to use Elvis operator "?."但是,建议使用猫王运算符“?”。 but in your case it's not possible due to the "-1" operation.但在您的情况下,由于“-1”操作,这是不可能的。 So you have to test props.error again:所以你必须再次测试 props.error:

In your case :在你的情况下:

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

I had a similar error when using map() on an array with possible different types.在可能具有不同类型的数组上使用map()时,我遇到了类似的错误。 You did a check for null and a check for an array so when those checks are passed you can be sure that your error props are an array of strings, you can do something like this:您检查了 null 并检查了一个数组,因此当这些检查通过时,您可以确定您的错误道具是一个字符串数组,您可以执行以下操作:

(props.error as string[]).map((item,index)

Or you can use the string[] directly on the props.error in your shorthand if statement或者您可以直接在简写 if 语句中的props.error上使用string[]

marginBottom={index === (props.error as string[]).length -1 ? "0px" : "8px"}

Adding an additional null check:添加额外的空检查:

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

Using the ! operator使用! operator ! operator to define this property as not null: ! operator将此属性定义为非空:

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

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

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