Typescript: How to type combined reducers?

雨燕双飞 提交于 2021-01-05 06:48:56

问题


I am migrating my small React Native project from pure Javascript to Typescript. While it went well so far, I now have problems with Redux.

The reducer I'm struggling with is radioButtonSelectedReducer. In the application, there are two radio buttons. If the first one is clicked, it gives string "itemOne" and if the second one is clicked, it gives string "itemTwo". Therefore, radioButtonSelected must be of type string, I thought. But it gives the error: radioButtonSelected: string; -->

"The expected type comes from property 'radioButtonSelected' which is declared here on type 'ReducersMapObject<IApplicationState, AnyAction>'" 

I am such a Typescript newbie and don't know what to do with this message.

imports ...

export interface IApplicationState {
  radioButtonSelected: string;
  searchBarInput: string;
  searchBarResult: string;
}

const rootReducer = combineReducers<IApplicationState>({
  radioButtonSelected: radioButtonSelectedReducer,
  searchBarInput: searchBarInputReducer,
  searchBarResult: searchBarResultReducer,
});

export type RootState = ReturnType<typeof rootReducer>; 

When I leave combineReducers() without <IApplicationState> and call RootState in mapStateToProps(), it gives the error:

  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.

Here is the snippet from the component that implements the radio buttons:

...

function mapStateToProps(state: RootState) {
  return {
    itemSelected: state.itemSelected,
  };
}

回答1:


You shouldn't have to declare IApplicationState or pass it as a generic to combineReducers(). In fact, that's explicitly the point of type RootState = ReturnType<typeof rootReducer>. It infers what the combined state type is, so you don't have to declare it or keep updating it.

Please refer to the Redux docs page on "Usage with TypeScript" for more details.



来源:https://stackoverflow.com/questions/60307199/typescript-how-to-type-combined-reducers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!