Blog>
Snippets

Configuring the Redux Store with TypeScript

Provide an example of configuring the Redux store applying TypeScript interfaces and types to create a robust and type-safe store configuration.
import { createStore, applyMiddleware, Store, AnyAction } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';

// Define the state type
interface AppState {
    counter: number;
}

// Define the initial state
const initialAppState: AppState = {
    counter: 0,
};

// Action Types
enum CounterActionTypes {
    INCREMENT = 'INCREMENT',
    DECREMENT = 'DECREMENT',
}

// Action Creators
interface IncrementAction {
    type: typeof CounterActionTypes.INCREMENT;
}

interface DecrementAction {
    type: typeof CounterActionTypes.DECREMENT;
}

type CounterActions = IncrementAction | DecrementAction;

// Reducer
function counterReducer(state: AppState = initialAppState, action: CounterActions): AppState {
    switch (action.type) {
        case CounterActionTypes.INCREMENT:
            return { ...state, counter: state.counter + 1 };
        case CounterActionTypes.DECREMENT:
            return { ...state, counter: state.counter - 1 };
        default:
            return state;
    }
}

// Configure Store
export function configureStore(): Store<AppState, AnyAction> {
    const store = createStore(
        counterReducer,
        composeWithDevTools(
            applyMiddleware(thunkMiddleware)
        )
    );
    return store;
}
This code snippet defines the structure of the AppState, an initialAppState, the available action types and their respective action interfaces. It also provides a reducer that handles the state based on the actions dispatched. Finally, it exports a configureStore function which creates a Redux store with the thunk middleware and Redux Dev Tools enabled for easy debugging.