HuolalaTech / react-query-kit

🕊️ A toolkit for ReactQuery that make ReactQuery hooks reusable and typesafe
MIT License
337 stars 11 forks source link

[Feature Request] Add new `inferOptions` util Typescript type #26

Closed snelsi closed 1 year ago

snelsi commented 1 year ago

Context

react-query-kit already provides 3 util types:

export type inferVariables<T> = ...;
export type inferData<T> = ...;
export type inferFnData<T> = ...;

Describe your proposal

Would be great to also provide inferOptions type, that would return QueryHookOptions or MutationHookOptions of the given hook.

You can kinda achieve similar result manually by doing:

type Options = QueryHookOptions<
  inferData<typeof usePost>,
  any,
  inferVariables<typeof usePost>,
  any
>;

or

type Options = MutationHookOptions<
  inferData<typeof usePost>,
  any,
  inferVariables<typeof usePost>,
  any
>;

But it's not super convenient.

Example of possible usage

// Define custom hook
const usePost = createQuery<Response, Variables, Error>({
  primaryKey: '/posts',
})

// Infer it's options
type usePostOptions = inferOptions<typeof usePost>

// Extend your hook 
const useExtendedPost = (options: usePostOptions) => usePost({ ...options, myExtraParam: true }) 
snelsi commented 1 year ago

Possible implementation:

export type inferOptions<T> = T extends QueryHook<infer TFnData, infer TVariables, infer TError>
? QueryHookOptions<TFnData, TError, TFnData, TVariables>
: T extends MutationHook<infer TData, infer TVariables, infer TError>
? MutationHookOptions<TData, TError, TVariables, any>
: never;
liaoliao666 commented 1 year ago

Available in v1.5.2