打字稿推断传递的泛型参数

时间:2021-06-15 08:37:01

标签: typescript redux typescript-typings

我正在编写 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的时候,想一起定义一个回调
  • 使用此应用键入时,我只想单独键入要传递给 api 层的有效负载。

1 个答案:

答案 0 :(得分:0)

您可以使用类型推断从 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
}