我正在将我的小型 React Native 项目从纯 Javascript 迁移到 Typescript。虽然到目前为止进展顺利,但我现在在使用 Redux 时遇到了问题。
我正在努力解决的 reducer 是 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,
};
}
最佳答案
您不必声明 IApplicationState
或将其作为泛型传递给 combineReducers()
。事实上,这正是 type RootState = ReturnType<typeof rootReducer>
的要点。 。它推断组合状态类型是什么,因此您不必声明它或不断更新它。
关于Typescript:如何输入组合 reducer ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60307199/