【问题标题】:Typescript infer passed generic parameter打字稿推断传递了通用参数
【发布时间】:2021-08-31 02:26:50
【问题描述】:

我在写redux saga常用函数。

interface WithCallback<T> {
  data: T
  onSuccess?: (data: T) => void
  onError?: (error: any) => void
}

function createSaga<
  RequestType,
  RequestPayload
>(...) {
  // ...
}

const saga = createSaga<string, WithCallback<{email: string}>}>(...)

如上代码,请问createSaga函数的参数中传递给RequestPayload参数的WithCallback类型的数据中,有什么方法可以推断出T吗?

或者有没有办法使用接收到的 RequestPayload 类型一起声明 WithCallback 泛型类型?

结论:

  • 定义redux action的时候,想一起定义一个回调
  • 当使用 this 应用类型时,我只想单独键入要传递给 api 层的有效负载。

【问题讨论】:

    标签: typescript redux typescript-typings


    【解决方案1】:

    您可以使用类型推断从WithCallback 中获取数据:

    // If you know it is a WithCallback and just want to get the inner type
    type CallbackData<T extends WithCallback<any>> =
        T extends WithCallback<infer D> ? D : never;
    
    // If you want to unwrap if it is a WithCallback otherwise keep the same type
    type CallbackData<T> =
        T extends WithCallback<infer D> ? D : T;
    

    我不是 Redux 开发人员,所以我不知道你会在哪里使用它,但它会是这样的:

    function createSaga<
      RequestType,
      RequestPayload
    >(input: RequestType): CallbackData<RequestPayload> {
      const result = {} as RequestPayload; // Get this from somewhere
    
      // Use the data, call the callbacks, make the world a better place...
    
      return result.data; // Assuming it will always be a WithCallback, you will need to check that at runtime since you RequestPayload can be any
    }
    

    【讨论】:

    • 感谢您为一个模棱两可的问题提供明确的答案。我尊重你的洞察力! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2022-11-26
    • 2018-11-01
    • 2019-07-30
    • 2021-07-17
    相关资源
    最近更新 更多