redux thunk - TypeScript, kiểm tra React thiếu kiểu trong AnyAction
Tôi đang gặp lỗi này:
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* :
* Mã của khai báo là:
export interface Action<T = any> {
type: T
}
AnyAction mở rộng Action.
Đây là mã của tôi trong bài kiểm tra:
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
Định nghĩa của signIn là:
export const signIn = () =>
async (dispatch: Dispatch): Promise<void> => {
dispatch({
type: SIGN_IN_REQUEST
});
};
Có gợi ý hay ý tưởng nào về cách sửa nó không?
Câu trả lời #1
configureStore cho phép chúng ta truyền các đối số vào các tiện ích mở rộng dispatch của express, vì vậy để nó hoạt động với redux-thunk, chúng ta phải chỉ định ThunkDispatch làm đối số như sau:
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>>([])
Câu trả lời #2
Như tmho2005 đã nói, tôi đã làm điều đó bằng cách đọc câu trả lời của anh ấy và một chủ đề tương tự khác. Đây là mã của tôi nếu ai đó muốn:
// 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'
}));
