【发布时间】:2021-02-07 23:58:46
【问题描述】:
我有以下异步操作定义:
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]
【问题讨论】:
-
Dispatch<any>不接受承诺。所以要么输入错误,要么你使用的库不正确。 -
我认为您使用了错误的 Dispatch。应该是
import { Dispatch } from "redux"。 -
我认为你应该从 thunk 导入 dispatch type
-
@HMR 我有
redux-thunk 2.30,那里没有Dispatch类型。我导入了一个ThunkDispatch类型并用作ThunkDispatch<any, any, any>,因为该类型是通用的并且需要三个类型参数(我不知道它们代表什么)。我收到一条不同的错误消息,但仍然没有运气。我会更新问题。 -
你能添加一个codesandbox吗?很难看出这一切是如何联系起来的,现在有点混乱。
标签: reactjs typescript redux axios redux-thunk