TypeScript: How to Properly Handle Union Types in a Redux Reducer State?
I'm maintaining legacy code that I tried several approaches but none seem to work. I'm working on a Redux reducer in my React application, and I'm having trouble correctly typing the state when it involves union types. I have a state that can either be an array of items or a loading state, and I'm not sure how to type it correctly without running into issues. Here's the relevant portion of my code: ```typescript interface Item { id: number; name: string; } type State = Item[] | 'loading'; type Action = { type: 'LOAD'; items: Item[] } | { type: 'LOADING' }; const initialState: State = 'loading'; const reducer = (state: State = initialState, action: Action): State => { switch (action.type) { case 'LOAD': return action.items; case 'LOADING': return 'loading'; default: return state; } }; ``` With this setup, I expected that `state` would correctly infer its type in the reducer based on the action dispatched. However, when I try to access properties on `state` later in my component, TypeScript doesnโt seem to recognize how to handle the union type properly. For instance: ```typescript const MyComponent: React.FC = () => { const items = useSelector((state: State) => state); return ( <div>{items.map(item => item.name).join(', ')}</div> ); }; ``` This leads to a TypeScript behavior: `Property 'map' does not exist on type 'Item[] | "loading"';`. I've tried adding type guards in the component, but it still feels clunky. Whatโs the best way to manage these union types in my Redux reducer and components? Any insights on how to improve type safety here would be appreciated. I'm using TypeScript 4.5.2 and React 17.0.2. I'm working on a web app that needs to handle this. Any help would be greatly appreciated! The project is a mobile app built with Typescript. Could someone point me to the right documentation?