I am trying to add typescript to redux toolkit app. This is a simple counter app, to increase or decrease the counter state by one.
import {
createSlice,
Dispatch,
PayloadAction
} from "@reduxjs/toolkit";
export interface CounterState {
value: number;
};
const initialState: CounterState = {
value: 0
};
export const counterSlice = createSlice({
name: 'Counter Slice',
initialState: initialState,
reducers: {
increment: (state) => {
state.value = state.value + 1;
},
decrement: (state) => {
state.value = state.value - 1;
},
incrementByAmount: (state, action: PayloadAction < number > ) => {
state.value = state.value + action.payload;
}
}
});
//What would be the type of "incrementAsync"
export const incrementAsync: any = (amount: number) => (dispatch: Dispatch) => {
setTimeout(() => {
dispatch(incrementByAmount(amount));
}, 1000);
};
export const {
increment,
decrement,
incrementByAmount
} = counterSlice.actions;
export default counterSlice.reducer;
What should be the type annotation for incrementAsync instead of the any type I have used just to make it work. The official redux toolkit documentation didn't help me.
The incrementAsync is just using a timeout function to increase the counter value by one after a delay of one second.