T
TanStack10mo ago
wise-white

How to annotate function, which returns queryOptions object.

Hello everyone, I have @typescript-eslint/explicit-module-boundary-types function enabled on my project. I want to create something like this:
function groupOptions() {
return queryOptions({
queryKey: ['groups'],
queryFn: fetchGroups,
staleTime: 5 * 1000,
})
}
function groupOptions() {
return queryOptions({
queryKey: ['groups'],
queryFn: fetchGroups,
staleTime: 5 * 1000,
})
}
But I am getting typescript error, because I need to define return type of groupOptions. I was unable to do it, as I get lots of errors from using groupOptions(): QueryOptions<ResponseData, etc, etc, etc> I cannot configure this rule to ignore those functions either. The only option, which I see right now is to declare my own interface for queryOptions:
type QueryOptionsAlternative<Response> = {
queryKey: unknown[]
queryFn: () => Promise<Response>
gcTime?: number
etc...
}
type QueryOptionsAlternative<Response> = {
queryKey: unknown[]
queryFn: () => Promise<Response>
gcTime?: number
etc...
}
Would you have any suggestions? Maybe I am missing something. It would be nice to use queryOptions helper, because it has better type safety.
3 Replies
wise-white
wise-whiteOP10mo ago
Yes, I found the option: This approach works well:
function groupOptions(): ReturnType<queryOptions> {
return queryOptions({
queryKey: ['groups'],
queryFn: fetchGroups,
staleTime: 5 * 1000,
})
}
function groupOptions(): ReturnType<queryOptions> {
return queryOptions({
queryKey: ['groups'],
queryFn: fetchGroups,
staleTime: 5 * 1000,
})
}
other-emerald
other-emerald10mo ago
But I am getting typescript error, because I need to define return type of groupOptions
that's not a typescript error, it's a lint error probably; using inference and not defining a return type is the better approach
wise-white
wise-whiteOP10mo ago
You're right, it's eslint error.
groupOptions(): ReturnType<queryOptions>
groupOptions(): ReturnType<queryOptions>
will keep inference. (I know it's redundant code in this case just to satisfy eslint rule, but I don't see better option)
groupOptions(): ReturnType<queryOptions>
groupOptions(): ReturnType<queryOptions>
It didn't work either. I agree, that in this case inference is better. Will try to figure out another approach

Did you find this page helpful?