RTK Query UseLazyQuery and Typescript: how to get the correct type from hook argument

Viewed 36

I need to create a react hook that accepts a RTK Query UseLazyQuery function (from any endpoint), apply a debounce to it and return the trigger function and results.

Everything is working as expected but I can't manage to get the correct type to the data returned by it.

As "UseLazyQuery" type requires a type for its generic type and I don't know what type it'll be, I set it to "any", but it makes the data to be typed as "any" too.

I need help to get/extract the correct type from the given "UseLazyQuery" function given to the hook and make the returned data have the correct type.

export default function useSearch<T extends UseLazyQuery<any>>(lazyQueryFn: T) {
  const [ trigger, results ] = lazyQueryFn()

  const getParamsAndTrigger = async (
    params: ISearchParamsRequest,
    filterParams?: (params: ISearchParamsRequest) => ISearchParamsRequest
  ) => {
    await trigger(filterParams ? filterParams(params) : params, true)
  }

  const debouncedTrigger = useDebouncedFn(getParamsAndTrigger, 1500)

  return [debouncedTrigger, { ...results }] as const
}

The "results" const returned by "lazyQueryFn" has the type "UseQueryStateDefaultResult". I need it to have the right data type.

0 Answers
Related