TypeScript Guide
TanStack Query is written in TypeScript and provides excellent type safety out of the box.Type Inference
TanStack Query infers types automatically from your query functions:Explicit Type Parameters
For more control, specify types explicitly:In most cases, you only need to specify the first type parameter (
TQueryFnData). The others can be inferred.Typing Query Keys
Strong typing for query keys helps prevent errors:Using queryOptions Helper
ThequeryOptions helper provides better type inference:
Typing Mutations
Mutations support full type safety for variables, data, and errors:Typing the QueryClient
The QueryClient is fully typed and provides type-safe methods:Typing Query Results with Initial Data
When providing initial data, the result type changes:With
initialData, the data property is never undefined, making it easier to work with.Type-Safe Select
Transform query data with full type safety:Discriminated Unions
Use TypeScript’s discriminated unions with query status:Generic Query Hook
Create reusable typed query hooks:Infinite Queries
Infinite queries have special type requirements:Best Practices
1
Define interfaces for your data
Create TypeScript interfaces for all API responses:
2
Use queryOptions for reusability
Create typed, reusable query configurations:
3
Let TypeScript infer when possible
Avoid over-specifying types. Let TypeScript infer from your query functions.
4
Use discriminated unions
Take advantage of status checks for better type narrowing.
Common Type Errors
”Type ‘undefined’ is not assignable to type…”
This happens when you forget thatdata can be undefined:
Next Steps
DevTools
Set up DevTools to inspect your typed queries
Essential Concepts
Review core concepts with TypeScript examples