网站搜索

redux thunk - TypeScript,react 测试中 AnyAction 缺失类型


我遇到了这个错误:

TS2345: Argument of type '(dispatch: Dispatch) => Promise<void>' is not assignable to parameter of
type 'AnyAction'.   Property 'type' is missing in type '(dispatch: Dispatch) => Promise<void>' but
required in type 'AnyAction'. type' is declared here* :

* 声明的代码是:

export interface Action<T = any> {
  type: T
}

AnyAction 继承自 Action。

这是我在测试中的代码:

import configureStore from 'redux-mock-store';
import reduxThunk from 'redux-thunk';
// some code, then in the test I have:

const mockStore = configureStore([reduxThunk]);
const store = mockStore({});

store.dispatch(signIn()); //here I have the error

signIn 的定义是:

export const signIn = () =>
  async (dispatch: Dispatch): Promise<void> => {
    dispatch({
      type: SIGN_IN_REQUEST
    });
  };

有没有关于如何修复它的提示或想法?

答案#1

configureStore 允许我们向 express dispatch 扩展传递参数,所以为了让它与 redux-thunk 一起工作,我们必须如下指定 ThunkDispatch 作为参数:

import { ThunkDispatch } from 'redux-thunk';

// your app state
interface AppState {}

// you can even express more params for `ThunkDispatch`
const mockStore = configureMockStore<AppState, ThunkDispatch<AppState, any, any>>([])

答案#2

正如 tmho2005 所说,我是通过阅读他的回答和另一个类似的帖子做到的。如果有人需要,这是我的代码:

// only relevant code for the question
import { AnyAction } from 'redux';
import configureStore from 'redux-mock-store';
import reduxThunk, { ThunkDispatch } from 'redux-thunk';

import { AuthState } from '../../../types'; // that's the definition of my app state

type DispatchExts = ThunkDispatch<AuthState, void, AnyAction>;

// And the code for mys tests:

const mockStore = configureStore<AuthState, DispatchExts>([reduxThunk]);
const store = mockStore(defaultState);

await store.dispatch(signIn({
  username: 'foo',
  password: 'bar'
}));