打字稿:如何输入组合减速器? [英] Typescript: How to type combined reducers?

查看:40
本文介绍了打字稿:如何输入组合减速器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的小型 React Native 项目从纯 Javascript 迁移到 Typescript.虽然到目前为止一切顺利,但我现在在使用 Redux 时遇到了问题.

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.

我正在努力使用的 reducer 是 radioButtonSelectedReducer.在应用程序中,有两个单选按钮.如果第一个被点击,它给出字符串itemOne",如果第二个被点击,它给出字符串itemTwo".因此,我认为 radioButtonSelected 必须是字符串类型.但它给出了错误:radioButtonSelected: string; -->

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>'" 

我是一个 Typescript 新手,不知道如何处理这条消息.

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>; 

当我离开 combineReducers() 而没有 并在 mapStateToProps() 中调用 RootState 时,它给出了错误:

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,
  };
}

推荐答案

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

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.

请参阅 Redux 文档页面使用 TypeScript"了解更多详情.

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

这篇关于打字稿:如何输入组合减速器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆