首页 > 解决方案 > 了解 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 接口。

如果有人可以为我解释这一点,那就太好了。

非常感谢。

标签: typescriptreduxredux-thunk

解决方案


默认情况下,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是一个具有两个不同重载的函数。


推荐阅读