Integrating TypeScript with Redux Store for Type Safety
Demonstrate how to integrate TypeScript with the Redux store for improved type safety and elimination of AnyAction.
import { createStore, Action, Reducer } from 'redux';
interface AppState {
counter: number;
}
interface IncrementAction extends Action<'INCREMENT'> {}
interface DecrementAction extends Action<'DECREMENT'> {}
type AppAction = IncrementAction | DecrementAction;
const initialState: AppState = {
counter: 0,
};
const reducer: Reducer<AppState, AppAction> = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, counter: state.counter + 1 };
case 'DECREMENT':
return { ...state, counter: state.counter - 1 };
default:
return state;
}
};
const store = createStore(reducer);
export default store;
Here we define the AppState interface to describe the shape of the application's state, and individual Action interfaces for each action type. We use a 'type' definition for AppAction that serves as a union of all action interfaces. The reducer is typed with both AppState and AppAction to ensure correct state and action types and is used to create the Redux store.
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
This part demonstrates dispatching actions of specific types to the store. The actions are type-checked against the AppAction union type, ensuring that they conform to the expected action structure.
import { Provider } from 'react-redux';
import store from './store';
import React from 'react';
import App from './App';
const Root: React.FC = () => (
<Provider store={store}>
<App />
</Provider>
);
export default Root;
This snippet integrates the Redux store with a React application by using the Provider component from react-redux. It wraps the App component ensuring that the store is available to all connected components in the component tree.