I have a problem adding a type to action.paload in the Redux Toolkit.
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
interface InputState {
user: {
firstName: string;
lastName: string | null;
userID: number | null;
};
}
const initialState: InputState = {
user: {
firstName: "individual",
lastName: null,
userID: null,
},
};
export const inputsDataSlice = createSlice({
name: "inputsData",
initialState,
reducers: {
setValue: (state, action: PayloadAction<string | number | null>) => {
const data: string = action.payload;
switch (data.id) {
case "firstName":
return void (state.user.firstName = data.value);
case "lastName":
return void (state.user.lastName = data.value);
case "userID":
return void (state.user.userID = data.value);
default:
return;
}
},
},
});
export const { setValue } = inputsDataSlice.actions;
export default inputsDataSlice.reducer;
data.id and data.value still show me an error: Property 'value' / 'id' does not exist on type 'string'
.
Where is the mistake please? With PayloadAction, I have exactly the specified types <string | number | null>
<string | number | null>
<string | number | null>
.
You yourself are specifying
const data: string = action.payload;
also, <string | number | null>
<string | number | null>
<string | number | null>
would mean that action.payload
is string
, number
or null
, not action.payload.value
, which you are accessing here by accessing data.value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.