了解 Redux Thunk Typescript 泛型和类型

Understanding Redux Thunk Typescript Generics and Types

我对 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) return是调度的操作对象。

<T extends A>(action: T): T; 行描述了该行为:

  • 我们派发一个action对象,对象的类型是T
  • dispatch 的 return 值是同一个对象

同样,对于<R>(asyncAction: ThunkAction<R, S, E, A>): R

  • R 是特定 thunk
  • 的 return 类型的通用参数
  • 当我们调度那个 thunk 时,dispatch(thunk()) returns thunk 的结果

是的,该语法表示 ThunkDispatch 是一个具有两个不同重载的函数。