4

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.

3
  • 1
    You're looking for typescriptlang.org/docs/handbook/… Commented Mar 29, 2019 at 16:33
  • 1
    Or type guards. Commented Mar 29, 2019 at 16:33
  • is there no way to do this without having to declare a kind: "red" within the Types? Commented Mar 29, 2019 at 17:08

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

"it doesn't make" 😕❓

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.