Stack Exchange
mapping three different types of component stored in one major state array?
I have the following code inside of my redux state module : this code is for an object the has an array that will have 3 different components inside :


export interface TypeA {
  id: string; 
  type : 'a'
  valueX : 'x'
}
export interface TypeB {
  id: string; 
  type : 'b'
  valueY : 'y'
}
export interface TypeC {
  id: string; 
  type : 'c'
  valueZ : 'z'
}

export interface MajorArr {
  types: {
    [key: string]: (TypeA | TypeB | TypeC)[];
  };
}



below is my mapping faction where I access this array and I want to map those 3 different components depending on the type of the item at current map iteration.
the current issue is el on map is giving the 3 items array but cannot know which one is being mapped, the props are different each time.


const typesItems = types[id].map((el) => {
        return (
          <TypeA id={el.id} valueY={el.valueY} />
          <TypeB id={el.id} valueX={el.valueX} />
          <TypeC id={el.id} valueZ={el.valueZ} />
        );
      }
    });




You could use a switch-case to check the type, and thus, render the right component and give the right props.
Something like
const typesItems = types[id].map((el) => {
        switch(el.type) {
          case 'a':
            return <TypeA id={el.id} valueX={el.valueX} />
          case 'b':
            return <TypeB id={el.id} valueY={el.valueY} />
          case 'c':
            return <TypeC id={el.id} valueZ={el.valueZ} />

          default: // Optionally handle unknown type
            return <></>;
      }
});


the props are diffrent each time Property 'Type' does not exist on type 'TypeA |TypeB | TypeC.

Looking your interfaces (in your first snippet) seems you have a type prop. Is not like that? If not, how the array you are mapping looks like? (i mean types[id] in your second snippet). I was thinking this was the type: (TypeA | TypeB | TypeC)[] (which has type in the all possibile elements)

You says "Property 'Type' does not exist on type 'TypeA |TypeB | TypeC.",  is the Upper T a typo? Cause the prop is type not Type.

Thanks I had issue with extended types by mistake... an eye opener !!

works... can I make a case that includes multi strings ? since one types has like 5 strings for one component ? but i dont want to copy it like  case 'a' | 'b' | 'c' | 'd' ect:

Yes, you can write multiple case lines and just one render after all of them.   Every case will render the same component.  (Cause, in a switch-case,  without a break or return, also the next cases will be executed, in this case, you'll have multiple cases empty and the last with the return, so all of them will fall in the same return)
