了解Redux Thunk打字稿泛型和类型

问题描述 投票:0回答:1

我对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中看到,调度始终是ThunkDispatch,但我无法辨认出是ThunkDispatch接口。

如果有人能为我解释这一点真是太棒了。

非常感谢。

typescript redux redux-thunk
1个回答
0
投票

默认情况下,store.dispatch(action)返回调度的操作对象。

[C0行描述了该行为:

  • 我们调度一个动作对象,并且对象的类型为<T extends A>(action: T): T;
  • 调度的返回值是相同的对象

类似地,对于T

  • <R>(asyncAction: ThunkAction<R, S, E, A>): R是特定重击的返回类型的通用参数
  • [当我们调度该thunk时,R返回该thunk的结果

是的,该语法表示dispatch(thunk())是具有两个不同的重载的函数。

© www.soinside.com 2019 - 2024. All rights reserved.