【问题标题】:How to infer generic paramter in return type in typescript如何在打字稿中推断返回类型中的泛型参数
【发布时间】:2020-09-12 02:31:30
【问题描述】:

我有一个类型

export type AppThunk<ReturnType> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

现在如果我像下面这样使用它

export const loadCourse = (id: string): AppThunk => {
  return (dispatch: Dispatch) => {
    dispatch(loadCourseSuccess(undefined));
    return api
      .getCourse(id)
      .then((course) => dispatch(loadCourseSuccess(course)));
  };
};

typescript 编译器报错,告诉我在 AppThunk 中提供泛型参数,如何让它自动推断泛型返回类型参数?

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    这里有三个不同的问题:

    • 如何在TS中正确定义和使用泛型参数
    • 如何正确定义和使用AppThunk类型
    • 如何在此处推断出正确的返回类型

    现在,您的 AppThunk 类型希望它必须被赋予一个通用参数 ReturnType。因此,您必须将其用作AppThunk&lt;TheActualReturnType&gt; - 在这种情况下,类似于AppThunk&lt;Promise&lt;void&gt;&gt;,因为您并没有真正从最终的.then() 返回任何内容。

    我们通常建议为 AppThunk 类型指定 `ReturnType 的默认值,因为许多 thunk 实际上并不返回任何内容,例如:

    export type AppThunk<ReturnType = void> = ThunkAction<
      ReturnType,
      RootState,
      unknown,
      Action<string>
    >;
    

    这样,您可以将其用作AppThunk,而无需指定返回类型。

    最后......使用AppThunk 的方式,我不认为它可以在这里推断出返回类型,因为你在告诉 TS 这个函数的类型是什么。

    【讨论】:

      【解决方案2】:

      如果您的目标是为 thunk 参数提供通用类型,但允许操作创建者推断其返回类型,您可以使用辅助函数来实现:

      export type AppThunk = ThunkAction<
        unknown,
        RootState,
        unknown,
        Action<string>
      >;
      
      export function enforceThunkType<T extends AppThunk>(thunk: T) {
        return thunk;
      };
       
      // explicitly types dispatch
      // while still infering the return type
      export const loadCourse = (id: string) => {
        return enforceThunkType((dispatch) => {
          dispatch(loadCourseSuccess(undefined));
          return api
            .getCourse(id)
            .then((course) => dispatch(loadCourseSuccess(course)));
        });
      };
      

      Inspired by / taken from this post

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-22
        • 2022-11-23
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多