I'm learning TypeScript, and when I try to set a reducer in redux Toolkit like this :
const testSlice = createSlice({
name: "test",
initialState: [],
reducers: {
callApi: (state, action) => {
const getData = {
type: "test/getData",
data: action.payload
};
state.push(getData);
}
}
});
I get state.push(getData)
underlined in red in VSCode, and the error : Argument of type 'any' is not assignable to parameter of type 'never'
I tried to write : const getData : any[] = {
but still have the same error.
Can someone tell me where is my mistake ?
Thank you !
CodePudding user response:
This is happening because you assign empty array to initialState without specifying its type. TS then inferring type as never[]
type TestState = any[];
const initialState: TestState = [];
const testSlice = createSlice({
name: "test",
initialState,
reducers: {
callApi: (state, action) => {
const getData = {
type: "test/getData",
data: action.payload
};
state.push(getData);
}
}
});
This should solve a problem, however I would recommend not using any
type