我有以下异步操作定义:
import {Dispatch} from 'react';
import axios, {AxiosResponse, AxiosError} from 'axios';
function asyncAction() {
return (dispatch: Dispatch<any>): Promise<number> => {
return axios.get('http://www.example.com')
.then( (res: AxiosResponse<any>) => {
return 1;
})
.catch( (err: AxiosError<any>) => {
return 2;
});
}
}
上面的类型检查很好。
我也明白当你调用dispatch并传递一个异步操作时,像这样:
dispatch(asynAction())
...然后是内部函数的返回类型,所以我希望上述值的类型是Promise<number>. 然而,以下不会进行类型检查:
function foo (dispatch: Dispatch<any>) {
const n: Promise<number> = dispatch(asyncAction()); // line A
}
具体来说,我收到以下错误line A:
TS2322: Type 'void' is not assignable to type 'Promise<number>'
所以,为了让 TS 满意,我不得不做类似下面这样感觉不对的事情:
const n: Promise<number> = dispatch(asyncAction()) as unknown as Promise<number>;
我错过了什么?
更新
我的`package.json` 有:"@types/react-redux": "^7.1.9",
"react-redux": "^7.2.0",
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0"
当我执行以下操作时:
import {ThunkDispatch as Dispatch} from 'redux-thunk';
...并使用导入的ThunkDispatch类型ThunkDispatch<any, any, any>(无论我Dispatch<any>在上面代码中的任何位置),如下所示:
import axios, {AxiosResponse
, AxiosError} from 'axios';
import {ThunkDispatch as Dispatch} from 'redux-thunk';
export function asyncAction() {
return (dispatch: Dispatch<any, any, any>): Promise<number> => {
return axios.get('http://www.example.com')
.then( (res: AxiosResponse<any>) => {
return 1;
})
.catch( (err: AxiosError<any>) => {
return 2;
});
}
}
export function foo (dispatch: Dispatch<any, any, any>) {
const n: Promise<number> = dispatch(asyncAction());
console.log(n);
}
......我得到了一个不同的错误:
TS2739: Type '(dispatch: ThunkDispatch<any, any, any>) => Promise<number>' is missing the following properties from type 'Promise<number>': then, catch, [Symbol.toStringTag]