Skip to main content

TypeScript

TanStack Query is written in TypeScript and provides excellent type safety out of the box.

Type Inference

React Query automatically infers types from your query functions:
The return type of queryFn determines the type of data. Add explicit Promise return types to your async functions for better type inference.

Generic Type Parameters

Explicitly specify types when automatic inference isn’t sufficient:

Type Parameters

Transforming Data

Use the select option to transform query data with full type safety:
The select function is memoized, so transformations only run when the underlying data changes.

Query Options Helper

Use queryOptions for reusable, type-safe query definitions:

Mutation Types

Type mutations for safe data updates:

Mutation Options Helper

Create reusable mutation configurations:

Infinite Queries

Type infinite scroll queries:

Type-Safe Query Keys

Define strongly-typed query keys:
Using as const ensures query keys are readonly tuples, providing better type inference and preventing accidental mutations.

Custom Hooks

Create type-safe custom hooks:

Error Types

Define custom error types:

Suspense Queries

Use suspense mode with full type safety:
useSuspenseQuery returns data that is never undefined, so you don’t need to handle the loading state manually.

Advanced Types

Narrowing Types

Discriminated Unions

Type Utilities

React Query exports helpful type utilities:
Always use import type for type-only imports to ensure they’re removed during compilation and don’t affect bundle size.

Next Steps

DevTools

Debug type issues with React Query DevTools

Server-Side Rendering

Type-safe SSR with Next.js