#reactjs #typescript #vue.js #react-redux
Вопрос:
У меня есть файл todoReducer.ts, подобный этому
import ActionType from "../types";
const initialState = {
items: [],
};
interface Item {
task: string;
priority: string;
id: string;
isActive: boolean;
label: string;
}
function reducer(state = initialState, action: any) {
switch (action.type) {
case ActionType.ADD_ITEM:
return { ...state, items: [action.payload, ...state.items] };
case ActionType.CROSS_ITEM:
return {
...state,
items: state.items.map((e: Item) => {
if (e.id === action.payload) e.isActive = false;
return e;
}),
};
default:
return state;
}
}
export default reducer;
Затем корневой редуктор, такой как этот
import { combineReducers } from "redux";
import authReducer from "./authReducer";
import todoReducer from "./todoReducer";
const reducers = combineReducers({
auth: authReducer,
todo: todoReducer,
});
export default reducers;
export type State = ReturnType<typeof reducers>;
В моем файле ToDoList.jsx
import {State} from "../store/reducers/index"
const TodoList = ()=>{
const items = useSelector((state:State) => state.todo.items);
...
}
Это дает мне ошибку
Свойство «элементы» не существует для типа «никогда».
Похоже items
, объект initialState не распознается ts.
Как мне устранить эту проблему?
Обновлено После комментария, я добавил
export type State = ReturnType<typeof store.getState>;
Но я навожу курсор на магазин.getState, он выдает ту же ошибку. Я все еще думаю, что он не выбирает тип
Ответ №1:
Вы должны объявить тип, когда createStore
const store = createStore(reducers, ...)
export type State = ReturnType<typeof store.getState>;
Комментарии:
1. Привет, Обновите вопрос, я думаю, что это место тоже не работает
Ответ №2:
Вы должны обновить typw для initialState
создания reducer
const initialState: Array<Item > = {
items: [],
};