As I delve into React-Redux
, I came across this example: https://redux-toolkit.js.org/usage/usage-with-typescript. I am following a step-by-step approach to build what I need. In a new file named infopieceSlice.ts, the following code was added:
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppThunk, RootState } from '../../store/store';
interface InfopieceState {
content: string[];
}
const initialInfopieceState: InfopieceState = {
content: [],
};
export const infopieceSlice = createSlice({
name: 'infopiece',
initialInfopieceState,
reducers: {
add: (InfopieceState, action: PayloadAction<string>) => {
InfopieceState.content.push(action.payload);
},
},
});
In the /store/store.ts file:
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
import logger from 'redux-logger';
export const store = configureStore({
reducer: {
counter: counterReducer,
},
middleware: getDefaultMiddleware =>
getDefaultMiddleware()
.concat(logger)
});
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>;
export type AppDispatch = typeof store.dispatch;
The errors encountered were:
src/features/counter/infopieceSlice.ts:19:3 - error TS2345: Argument of type '{ name:
string; initialInfopieceState: InfopieceState; reducers: { add: (InfopieceState: unknown,
action: { payload: string; type: string; }) => void; }; }' is not assignable to parameter of
type 'CreateSliceOptions<unknown, SliceCaseReducers<unknown>, string>'.
Object literal may only specify known properties, and 'initialInfopieceState' does not
exist in type 'CreateSliceOptions<unknown, SliceCaseReducers<unknown>, string>'.
19 initialInfopieceState,
~~~~~~~~~~~~~~~~~~~~~
src/features/counter/infopieceSlice.ts:22:7 - error TS2571: Object is of type 'unknown'.
22 InfopieceState.content.push(action.payload);
The code snippet for creating React app with Redux TypeScript template is as follows (suggested at: https://redux-toolkit.js.org/introduction/getting-started):
npx create-react-app my-app --template redux-typescript
:
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppThunk, RootState } from '../../store/store';
interface CounterState {
value: number;
}
const initialState: CounterState = {
value: 0,
};
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload;
},
},
});
The goal is to define InfopieceState and infopieceSlice that handle string[] data types. How can the type issues be resolved?