我收到一个 Typescript 错误,我在 Redux 中使用的对象可能未定义,即使我没有说它的类型可以未定义或在任何地方将其设置为未定义。
/redux/globalSettings/actions.ts
import { ADD_GLOBAL_SETTINGS } from '../../config/actions';
import { AddGlobalSettingsAction } from './types';
import GlobalSettings from '../../typings/contentful/GlobalSettings';
export const addGlobalSettings = (payload: GlobalSettings): AddGlobalSettingsAction => ({
type: ADD_GLOBAL_SETTINGS,
payload,
});
/redux/globalSettings/reducers.ts
import { ADD_GLOBAL_SETTINGS } from '../../config/actions';
import { GlobalSettingsAction, GlobalSettingsState } from './types';
export default (
state: GlobalSettingsState,
action: GlobalSettingsAction,
): GlobalSettingsState => {
switch (action.type) {
case ADD_GLOBAL_SETTINGS:
return { ...action.payload };
default:
return state;
}
}
/redux/globalSettings/types.ts
import { ADD_GLOBAL_SETTINGS } from '../../config/actions';
import GlobalSettings from '../../typings/contentful/GlobalSettings';
export type GlobalSettingsState = GlobalSettings;
export interface AddGlobalSettingsAction {
payload: GlobalSettings;
type: typeof ADD_GLOBAL_SETTINGS;
}
export type GlobalSettingsAction = AddGlobalSettingsAction;
/redux/reducer.ts
import { combineReducers } from 'redux';
import globalSettings from './globalSettings/reducers';
const rootReducer = combineReducers({
globalSettings,
});
export type StoreState = ReturnType<typeof rootReducer>;
export default rootReducer;
/redux/index.ts
import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import rootReducer, { StoreState } from './reducer';
我通过在next-redux-wrapper我的_app.js页面导出时使用NPM 包(一个 React HOC)在我的 NextJS 项目中使用它,如下所示:
export default withRedux(initialiseStore)(Page);
我在/redux/reducer.ts得到一个错误:Type 'undefined' is not assignable to type 'GlobalSettings'。
如果我globalSettings在我的一个页面上使用redux 状态,访问globalSettings.fields.navigationLinks会创建另一个globalSettings可能未定义的Typescript 错误。
让我发疯,我在这里做错了什么?
紫衣仙女
相关分类