How to properly type the useQueries hook? #3991
-
Ultimately this doesn't matter that much to me since I can just write an endpoint for this to use with Typescript successfully infers the type of this variable based on the return of // test: [UseQueryResult<SomeInterface, unknown>]
let test = useQueries({
queries: ids.map((id) => {
return {
queryKey: ["key", id],
queryFn: api.someFunc(id),
};
}),
}); However, if I explicitly tell // test: UseQueryResult<SomeInterface, unknown>[]
let test = useQueries({
queries: ids.map<UseQueryOptions<SomeInterface>>((id) => {
return {
queryKey: ["id", id],
queryFn: api.someFunc(id),
};
}),
}); Even without a map, typing // test: UseQueryResult<unknown, unknown>[]
let test = useQueries<SomeInterface[]>({
queries: [
{
queryKey: ["id", ids[0]],
queryFn: api.someFunc(ids[0]),
},
],
}); I'm not sure if this is an issue or if I'm just using it wrong. I would think this should work similarly to a typed |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
seems like a bug in the types (they are rather complex) here is a simple typescript playground showing the issue. @artysidorenko fyi |
Beta Was this translation helpful? Give feedback.
-
Hi @tomashaddad , yes to be honest at the time I hand't yet taken into consideration the need for explicit-typing-with-dynamic-size-arrays, those explicit type params were intended more as an escape hatch in case the automatic inference didn't work. A. What was built originally, but not a good solution: If your input B. Not well-documented, but actually works best: If you pass type TQueries = UseQueryOptions<SomeInterface>[]
// test: UseQueryResult<SomeInterface, unknown>[]
let test = useQueries<TQueries>({
queries: [
{
queryKey: ["id", ids[0]],
queryFn: api.someFunc(ids[0]),
},
],
}); Here's @TkDodo 's playground with the working solution added below |
Beta Was this translation helpful? Give feedback.
Hi @tomashaddad , yes to be honest at the time I hand't yet taken into consideration the need for explicit-typing-with-dynamic-size-arrays, those explicit type params were intended more as an escape hatch in case the automatic inference didn't work.
A. What was built originally, but not a good solution:
If your input
queries
are a fixed array of known length, it would accept a couple of different options, that both get really ugly really fast (a fixed length 2-dimensional array, or an array of object type-maps... some examples of the former and the latter, just in case you're curious).. these only works for fixed length inputs anyway.B. Not well-documented, but actually works best:
If yo…