问题
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