简体   繁体   English

如何在 TypeScript 中映射多种类型的数组?

[英]How to map over array of multiple types in TypeScript?

If I have a variable whose type is an array that can take multiple types…如果我有一个变量,它的类型是一个可以采用多种类型的数组……

type myData = (RedType | BlueType)[];
//`const data` is of type myData

And I am performing a manual check on the types with a conditional to do some logic on the variable data…我正在对类型进行手动检查,并有条件地对变量数据执行一些逻辑......

     {data.map((element, index) => {
        if (isRed(element)) {
          return <Red data={element} key={index} />;
        } else {
          return <Blue data={element} key={index} />;
        }
      })}

As you can see, I am mapping the array and I return one Component if it is a RedType and I return something else for the BlueType.如您所见,我正在映射数组,如果它是 RedType,则返回一个 Component,并为 BlueType 返回其他内容。

However, typescript doesn't like this, it doesn't know I am manually doing a conditional.但是,打字稿不喜欢这样,它不知道我正在手动执行条件。 So it errors:所以它错误:

type ‘RedType | BlueType’ is not assignable to type ‘RedType’.  

And vise versa.反之亦然。

I will always have an array of multiple types, that I cannot change.我将始终拥有多个类型的数组,我无法更改。

You probably want your isRed() function to be a user-defined type guard .您可能希望您的isRed()函数是用户定义的类型保护 That is, change its signature to be something like也就是说,将其签名更改为类似

declare function isRed(x: any): x is RedType;

and your code should start compiling with no error.并且您的代码应该开始编译而不会出错。 Hope that helps;希望有所帮助; good luck!祝你好运!

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

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