如何调度 Action 或 ThunkAction(在 TypeScript 中,使用 redux-thunk)? [英] How to dispatch an Action or a ThunkAction (in TypeScript, with redux-thunk)?
问题描述
假设我有这样的代码:
import { Action, Dispatch } from 'redux';
import { ThunkAction } from 'redux-thunk';
interface StateTree {
field: string;
}
function myFunc(action: Action | ThunkAction<void, StateTree, void>,
dispatch: Dispatch<StateTree>) {
dispatch(action); // <-- This is where the error comes from
}
...我从 TypeScript 编译器中得到这个错误:
...I get this error from the TypeScript compiler:
ERROR in myFile.ts:x:y
TS2345: Argument of type 'Action | ThunkAction<void, StateTree, void>' is not assignable to parameter of type 'Action'.
Type 'ThunkAction<void, StateTree, void>' is not assignable to type 'Action'.
Property 'type' is missing in type 'ThunkAction<void, StateTree, void>'.
我认为问题是因为 redux-thunk
类型定义文件增强了 redux
Dispatch
接口的方式和 TypeScript 的无能知道要使用哪个 Dispatch
定义.
I believe the problem is because of the way the redux-thunk
type definition file augments the redux
Dispatch
interface and the inability for TypeScript to know which definition of Dispatch
to use.
有没有办法解决这个问题?
Is there a way around this?
推荐答案
我认为您是对的,尽管能够处理这两种类型,但 typescript 无法确定使用哪种重载.
I think you are correct in that despite being able to handle both types, typescript cannot work out which overload to use.
我认为对您来说最好的选择是在调用 dispatch
I think the best option for you is to cast back to the desired type when calling dispatch
function myFunc(action: Action | ThunkAction<void, StateTree, void>,
dispatch: Dispatch<StateTree>) {
if (action instanceof ThunkAction<void, StateTree, void>) {
dispatch(action as ThunkAction<void, StateTree, void>);
} else {
dispatch(action as Action);
}
}
我希望我错了,有更好的方法来实现这一点.
I hope I'm wrong and there is a better way to achieve this.
这篇关于如何调度 Action 或 ThunkAction(在 TypeScript 中,使用 redux-thunk)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!