Skip to main content

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:
Use type assertions in your query function to inform TypeScript about the returned data shape.

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

The queryOptions helper provides better type inference:
Use queryOptions to create reusable, well-typed query configurations that can be shared across components.

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:
Always provide initialPageParam when using useInfiniteQuery to ensure proper typing.

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 that data can be undefined:
Use the status field or provide initialData to avoid undefined checks.

Next Steps

DevTools

Set up DevTools to inspect your typed queries

Essential Concepts

Review core concepts with TypeScript examples