【问题标题】:How to createStore with composeWithDevTools in Typescript without type errors?如何在 Typescript 中使用 composeWithDevTools 创建存储而不会出现类型错误?
【发布时间】:2020-01-29 13:02:21
【问题描述】:

在我的 index.tsx 中,我创建了 redux 存储

import { createStore, Store } from 'redux';
...
const store: Store = createStore(reducers, {});

现在我尝试添加 composeWithDevTools

import { createStore, Store, compose } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
...
const store: Store = createStore(reducers, {}, compose(composeWithDevTools()));

我得到的是错误

Type 'Store<CombinedState<{ general: any; }>, StoreAction>' is not assignable to type 'Store<any, AnyAction>'.
  Types of property 'dispatch' are incompatible.
    Type 'Dispatch<StoreAction>' is not assignable to type 'Dispatch<AnyAction>'.
      Type 'AnyAction' is not assignable to type 'StoreAction'.  TS2322

看起来它与我的 StoreAction 类型有某种关系。 在我的减速器中,我有以下内容

export default (state: GeneralState = initialState, action: StoreAction) => {
...
};

StoreAction 是

type StoreAction = {
  type: string;
  payload: any;
};

而且这个 StoreAction type 与 AnyAction interface 不兼容。我不明白如何从 TypeScript 的角度正确修复它。

有什么办法可以解决这个错误吗?

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    您似乎不需要将composeWithDevTools 包装在compose 语句中。

    来自文档:

      const composedEnhancers = composeWithDevTools(...enhancers)
      const store = createStore(rootReducer, preloadedState, composedEnhancers)
    

    https://redux.js.org/recipes/configuring-your-store/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2018-12-07
      相关资源
      最近更新 更多