While I have come across similar questions on this topic, I couldn't find one that addresses my specific case or that I fully comprehend. Let me explain the situation and share the code:
1. I have a React component that receives a store as a prop. 2. This store has a "tab" property which can be either "points", "segments", or "tags". 3. Additionally, the store contains arrays for points, segments, or tags, each of type Array. 4. Within my component, I need a variable named "selectedEntity" that could belong to any of these types. To achieve this, I initially declared it without specifying the type and then attempted to assign the appropriate value and type within a switch statement. However, TypeScript is raising complaints. Even after assignments and type assertions, TypeScript continues to flag 'selectedEntity' as being of type any.
Code:
const TagCustomization: React.FC<PropsType> = ({ store, curr }) => {
let selectedEntities;
let thisEntity;
let thisTag;
useEffect(() => {
switch (store.tab) {
case "points":
selectedEntities = store.points.filter(
(point) => point.selected,
) as Array<Tpoint>;
thisEntity = selectedEntities[curr] as Tpoint;
thisTag = store.tags.find(
(tag) => tag.id == thisEntity.id,
);
break;
// The same issue occurs in the cases below
case "segments":
selectedEntities = store.segments.filter(
(seg) => seg.selected,
) as Array<Tsegment>;
thisEntity = selectedEntities[curr] as Tsegment;
thisTag = store.tags.find(
(tag) => tag.id == thisEntity.id,
);
break;
case "tags":
selectedEntities = store.tags.filter(
(tag) => tag.selected,
) as Array<Ttag>;
thisEntity = selectedEntities[curr] as Ttag;
thisTag = thisEntity;
break;
}
}
}, [store.tab, curr]);
...
How can I clearly define the types of selectedEntities and thisEntity inside and outside the switch statement to resolve this TypeScript error?