Integrating createAction with TypeScript
Demonstrate creating typed Redux action creators with createAction and handling them in reducers, with proper type inference.
import { createAction, createReducer, PayloadAction } from '@reduxjs/toolkit';
// Defining the type for our payload
interface Todo {
id: number;
text: string;
completed: boolean;
}
// Creating the action creator with createAction
const addTodo = createAction<Todo>('ADD_TODO');
// Initial state for the reducer
const initialState: Todo[] = [];
// Reducer with createReducer function using inferred types
const todosReducer = createReducer(initialState, {
// Handling the action type with correct payload type
[addTodo.type]: (state, action: PayloadAction<Todo>) => {
// 'action.payload' is correctly inferred to be a 'Todo' type
state.push(action.payload);
}
});
// Exporting the action creator and reducer
export { addTodo, todosReducer };
This code snippet uses Redux Toolkit's createAction and createReducer to create a typed action and reducer for a Todos application. It defines the Todo interface for the action's payload, creates an action using createAction, and reduces it with the correct payload type using createReducer.