Blog>
Snippets

Typing Redux Reducers Post-AnyAction

Provide an example of a Redux reducer function that uses specific action types instead of the generic AnyAction.
// Define action types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

// Create an interface for the state
interface CounterState {
    count: number;
}

// Define interfaces for each action
interface IncrementAction {
    type: typeof INCREMENT;
}

interface DecrementAction {
    type: typeof DECREMENT;
    payload: number;
}

// Combine action interfaces using a type union
type CounterActions = IncrementAction | DecrementAction;

// Initial state
const initialState: CounterState = {
    count: 0,
};

// Reducer function with specific action types
function counterReducer(
    state: CounterState = initialState,
    action: CounterActions
): CounterState {
    switch (action.type) {
        case INCREMENT:
            return { count: state.count + 1 };
        case DECREMENT:
            return { count: state.count - action.payload };
        default:
            return state;
    }
}
This Redux reducer named 'counterReducer' specifically handles two action types: 'INCREMENT' and 'DECREMENT'. It uses TypeScript interfaces to type the state and actions. The 'INCREMENT' action increases the count by 1, while the 'DECREMENT' action decreases the count by a payload value. The reducer ensures type-safe handling of actions and returns the new state accordingly.