有什么方法可以从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) => { ... }
答案 0 :(得分:2)
默认导出为createMockStore
的{{1}}函数接受通用类型redux-mock-store
,其中<S, DispatchExts>
是Redux状态的定义,而S
是任何添加的Redux中间件的(或单个)附加DispatchExts
签名的并集。
因此,进行此设置的方法是从Dispatch
导入ThunkDispatch
,后者接受自己的redux-thunk
通用参数,并将其作为<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
的定义https://github.com/reduxjs/redux-thunk/blob/master/index.d.ts
ThunkDispatch
定义https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/redux-mock-store/index.d.ts
答案 1 :(得分:2)
对于configureMockStore
使用,解决方案几乎与上面完全相同。
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
的两个示例
答案 2 :(得分:0)
在类似的情况下,我发现了用Typescript编写的库的最新版本,并且与redux(4.0.4
)和redux-thunk 2.3.0
的最新版本一起使用时效果更好。