Typescript:如何输入组合减速器?

Run*_*ror 2 typescript redux react-redux

我正在将我的小型 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>'" 
Run Code Online (Sandbox Code Playgroud)

我是 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>; 
Run Code Online (Sandbox Code Playgroud)

当我离开combineReducers()<IApplicationState>调用RootStatemapStateToProps(),它给出了错误:

  error TS2339: Property 'itemSelected' does not exist on type 'CombinedState<{ radioButtonSelected: { itemSele
cted: string; }; searchBarInput: { inputValue: any; }; searchBarResult: { returnValue: any; }; }>'.
Run Code Online (Sandbox Code Playgroud)

以下是实现单选按钮的组件的片段:

...

function mapStateToProps(state: RootState) {
  return {
    itemSelected: state.itemSelected,
  };
}
Run Code Online (Sandbox Code Playgroud)

mar*_*son 5

您不必将IApplicationState其作为泛型声明或传递给combineReducers(). 事实上,这正是 的重点type RootState = ReturnType<typeof rootReducer>。它推断组合状态类型是什么,因此您不必声明它或不断更新它。

请参阅Redux 文档页面上的“使用 TypeScript”了解更多详细信息。