我正在将我的小型React Native项目从纯Javascript迁移到Typescript。尽管到目前为止进展顺利,但我现在对Redux遇到了问题。
我正在努力使用的减速器是radioButtonSelectedReducer
。在应用程序中,有两个单选按钮。如果单击第一个,则给出字符串“ itemOne”,如果单击第二个,则给出字符串“ itemTwo”。因此,我认为radioButtonSelected
必须是字符串类型。但是它给出了错误:radioButtonSelected: string;
->
"The expected type comes from property 'radioButtonSelected' which is declared here on type 'ReducersMapObject<IApplicationState, AnyAction>'"
我真是一名Typescript新手,不知道如何处理此消息。
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>;
当我离开combineReducers()
而没有<IApplicationState>
并在RootState
中调用mapStateToProps()
时,会出现错误:
error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.
这是实现单选按钮的组件的片段:
...
function mapStateToProps(state: RootState) {
return {
itemSelected: state.itemSelected,
};
}
答案 0 :(得分:3)
您不必声明IApplicationState
或将其作为泛型传递给combineReducers()
。实际上,这显然是type RootState = ReturnType<typeof rootReducer>
的重点。它可以推断出组合状态类型是什么,因此您不必声明它或继续更新它。
有关更多详细信息,请参阅the Redux docs page on "Usage with TypeScript"。