Capítulo 6 de 80
Types flow through useQuery/useMutation automatically from a well-typed queryFn/mutationFn — you rarely annotate generics by hand — and the Register interface lets you set app-wide defaults for the error, meta, and key types instead of repeating them per call.
data's type is inferred from queryFn's return type; select narrows it further. Type it by giving queryFn a real return type, not by annotating useQuery generics.status/derived booleans (isSuccess, etc.) — narrowing on isSuccess makes data non-undefined without a manual assertion.Error: override per-call via generics (loses inference for the rest), or globally via declare module '@tanstack/react-query' { interface Register { defaultError: MyError } }.Register interface: the mechanism for registering app-wide defaultError, queryMeta/mutationMeta (must extend Record<string, unknown>), and queryKey/mutationKey (must extend Array) types once, applied everywhere.queryOptions/mutationOptions helpers: extracting options into a shared function loses inference unless wrapped in these helpers — they also make the returned queryKey "know" its associated data type, so queryClient.getQueryData(opts.queryKey) comes back typed.// Global error type — forces explicit narrowing at every call site
declare module '@tanstack/react-query' {
interface Register {
defaultError: unknown
}
}
// queryOptions preserves inference when extracted into a shared function
function groupOptions() {
return queryOptions({ queryKey: ['groups'], queryFn: fetchGroups, staleTime: 5000 })
}
useQuery(groupOptions())
const data = queryClient.getQueryData(groupOptions().queryKey) // typed, not unknown
useQuery and direct queryClient calls.useQuery generics — fix the queryFn's return type instead, inference flows from there.queryOptions/mutationOptions the moment options are extracted out of the component that calls useQuery/useMutation — it's the difference between a typed queryKey and an unknown one at every other call site.Register is the one-time, app-wide way to set error/meta/key types; reach for per-call generics only for a genuine one-off exception.queryOptions/mutationOptions are used day to day.skipToken, the type-safe way to disable a query conditionally.