Get type of QueryResult from queryOptions? #8651
Answered
by
TkDodo
Faithfinder
asked this question in
Q&A
|
Is there a helper type like this? const todoQueryOptions = (params) => queryOptions({ queryKey, queryFn});
type TodoQueryResult = InferQueryResult<ReturnType<typeof todoQueryOptions>> |
Answered by
TkDodo
Mar 18, 2025
Replies: 4 comments 5 replies
|
Also just ran into this. Haven't been able to figure out a solution |
0 replies
|
why do you need that? Inference is complicated 😅 |
4 replies
|
@TkDodo I want to get the return type of the queryFn from the options. Use case:
|
1 reply
|
If anyone stumbles across this and you are interested on inferring the type of the data directly from the query options. I came up with this utility type. type InferQueryData<T> =
T extends (...args: any) => { select?: (...args: any) => infer S} ? S:
T extends (...args: any) => { queryFn?: (...args: any) => infer R} ? Awaited<R>: never; Example: function getTodoById(id: number) {
return queryOptions({
queryKey: ['todo', id],
queryFn: () => Promise.resolve({ data: 5 }),
select: (result) => result.data
})
};
function getTodoByIdWithoutSelect(id: number) {
return queryOptions({
queryKey: ['todo', id],
queryFn: () => Promise.resolve({ data: 5 }),
})
};
// number
type TodoWithSelect = InferQueryData<typeof getTodoById>
// { data: number }
type TodoWithoutSelect = InferQueryData<typeof getTodoByIdWithoutSelect>This could be useful when your types are automatically generated from a Open API spec. Of course you could also just move the declaration of the query function outside and export its return type... |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

this works fine with just
type TodoQueryOptions = ReturnType<typeof todoQueryOptions>:https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgRwK4FMoE8DyYbAQB2AzgDRyonoCKG2cAvnAGZQQhwDkAAjAIakBAYwDWAeijp+wmAFo0mLFwBQoSLDgAqOPxJwAStNmt2nLlJkxVK4cRLwYEACYQ6SvAXtwAvHAAUwM4AXHBEqCAARpgAlL4AfCj0uPiEpP4IKnBJSgDS6FihANpcTq5cFEEAumRZOdgAYkSh-nE+iQAKZsDUAHRSJBAANgBu6IHOMSqMMQDcKiowWGDocAAqLm7Jnmn6fkYwqFBEa8voADxLKxAscGVbHqn28QssqESyaXAAgmBgrYgFtk7EI4EUghRqDAAJLOKq+QzGGC9KjoADKAhg4wADFNgfZHJsdt4-Pd3NhiekglM6lJDscAnVsudnMARi9spy4OcALJYADCHEgRHQRHgECepB8CHulJIzHEHM553ErPZdSmjFe70+xDgfMF4GIopg-jA7DAJFCCAlXlIoQ2rnJKTt8rimTqIIc9SwCNRzrNFpIvVtuxp2TpRyIYVQQyG0xUQA