有没有办法从使用 redux-mock-store 创建的商店中正确调度 Thunk?现在我被迫使用任何类型的断言
store.dispatch<any>(getCommissions());
正如dispatch
期望的那样,提供简单的行动
[ts]
Argument of type '(dispatch: ThunkDispatch<IRootState, undefined,
AnyAction>, getState: () => IRootState) => void' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type '(dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => void'.
getCommisions()
的代码片段
export function getCommissions() {
return (dispatch: ThunkDispatch<IRootState, undefined, AnyAction>, getState: () => IRootState) => { ... }
作为redux-mock-store
默认导出的createMockStore
函数接受泛型类型<S, DispatchExts>
其中S
是 Redux 状态的定义,DispatchExts
是任何添加的 Redux 中间件的(或单个(附加Dispatch
签名的联合。
所以设置它的方法是从redux-thunk
导入ThunkDispatch
,它接受自己的泛型<State, ExtraArgument, Action>
参数并将其作为DispatchExts
参数传递给createMockStore
。
下面是一个缩写示例:
import { AnyAction } from 'redux'; // Or your own Action definition
import createMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';
import { ApplicationState } from '../your/definitions';
type DispatchExts = ThunkDispatch<ApplicationState, void, AnyAction>;
const middleware = [thunk];
const mockStore = createMockStore<ApplicationState, DispatchExts>(middleware);
const store = mockStore();
希望对您有所帮助!
我当前的版本:redux 4.0.0
redux-thunk 2.3.0
redux-mock-store 1.5.3
typescript 2.9.2
ThunkDispatch
定义 https://github.com/reduxjs/redux-thunk/blob/master/index.d.ts
createMockStore
定义 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/redux-mock-store/index.d.ts
对于configureMockStore
使用,解决方案几乎与@nickpassarella的答案完全相同。
import configureMockStore from 'redux-mock-store';
import thunk, { ThunkDispatch } from 'redux-thunk';
import { MyState, MyActions } from './my-types';
type DispatchExts = ThunkDispatch<MyState, undefined, MyActions>;
const middlewares = [thunk];
const mockStore = configureMockStore<MyState, DispatchExts>(middlewares);
const store = mockStore();
使用redux 4.0.1
redux-thunk 2.3.0
redux-mock-store 1.5.3
和typescript 3.5.3
的两个示例
在类似的情况下,我发现了用 Typescript 编写的库的最新分支,并且可以更好地与最新版本的 redux (4.0.4
( 和 redux-thunk2.3.0
一起使用。
https://github.com/jedmao/redux-mock-store