Get type of QueryResult from queryOptions? #8651
-
|
Is there a helper type like this? const todoQueryOptions = (params) => queryOptions({ queryKey, queryFn});
type TodoQueryResult = InferQueryResult<ReturnType<typeof todoQueryOptions>> |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
|
Also just ran into this. Haven't been able to figure out a solution |
Beta Was this translation helpful? Give feedback.
-
|
why do you need that? Inference is complicated 😅 |
Beta Was this translation helpful? Give feedback.
-
|
@TkDodo I want to get the return type of the queryFn from the options. Use case:
|
Beta Was this translation helpful? Give feedback.
-
|
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... |
Beta Was this translation helpful? Give feedback.

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