user10741122
user10741122

Reputation: 891

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.

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.

Upvotes: 4

Views: 5811

Answers (1)

jcalz
jcalz

Reputation: 328302

You probably want your isRed() function to be a user-defined type guard. 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!

Upvotes: 2

Related Questions