typescript - 了解 Redux Thunk Typescript 泛型和类型
问题描述
我对 Typescript 中 Redux Thunk 的语法有点困惑。我对 Typescript 很陌生,但对它有很好的掌握,但有一个特定的部分我不明白。
这是 redux-thunk 的类型定义文件:
import { Middleware, Action, AnyAction } from "redux";
export interface ThunkDispatch<S, E, A extends Action> {
<T extends A>(action: T): T; // I don't understand this line
<R>(asyncAction: ThunkAction<R, S, E, A>): R; // or this line
}
export type ThunkAction<R, S, E, A extends Action> = (
dispatch: ThunkDispatch<S, E, A>,
getState: () => S,
extraArgument: E
) => R;
export type ThunkMiddleware<S = {}, A extends Action = AnyAction, E = undefined> = Middleware<ThunkDispatch<S, E, A>, S, ThunkDispatch<S, E, A>>;
declare const thunk: ThunkMiddleware & {
withExtraArgument<E>(extraArgument: E): ThunkMiddleware<{}, AnyAction, E>
}
export default thunk;
我感到困惑的部分是:
<T extends A>(action: T): T; // I don't understand this line
<R>(asyncAction: ThunkAction<R, S, E, A>): R; // or this line
我查看了文档,它显示了这一点:
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn<number> = identity;
这是否意味着 ThunkDispatch 是一个函数,并且它可以遵循这两个函数签名中的任何一个?
我可以从 Thunk Action 中看到,dispatch 总是一个 ThunkDispatch,但我看不出来的是 ThunkDispatch 接口。
如果有人可以为我解释这一点,那就太好了。
非常感谢。
解决方案
默认情况下,store.dispatch(action)
返回分派的动作对象。
该行<T extends A>(action: T): T;
描述了该行为:
- 我们 dispatch 一个 action 对象,对象的类型是
T
- dispatch 的返回值是同一个对象
同样,对于<R>(asyncAction: ThunkAction<R, S, E, A>): R
:
R
是特定 thunk 的返回类型的通用参数- 当我们派发那个 thunk 时,
dispatch(thunk())
返回 thunk 的结果
是的,该语法是说这ThunkDispatch
是一个具有两个不同重载的函数。
推荐阅读
- javascript - 获取图像元素的第一个 src
- python - 在 google colab 上保存对克隆的 repo 的更改
- math - MIPS Mars4.5 保存算术项中的第一个数字
- angularjs - $http - post - 错误请求错误未处理(未定义)
- mnemonics - 我有 BIP39 助记符,需要 BIP44 xpub
- datetime - 检查时间戳是否为 1 小时前 - Groovy
- python - 在 tkinter 中单击按钮后如何更新值
- python - 配置不当的django错误
- ruby-on-rails-3 - Rails 5.2:开始使用新的加密凭证功能后,GCP 部署失败
- r - 尝试安装私有 Gitlab R 包时由对等方重置连接