Skip to main content

TypeScript

Vue Query is written in TypeScript and provides comprehensive type safety with excellent inference. This guide covers TypeScript patterns and best practices.

Type Inference

Vue Query automatically infers types from your query and mutation functions:
Always specify return types for your query functions. This ensures type safety throughout your application and provides better error messages.

Generic Type Parameters

useQuery accepts four generic type parameters for explicit typing:
  • TQueryFnData: The type returned by the query function
  • TError: The type of errors (defaults to DefaultError)
  • TData: The type of the final data (after select transforms)
  • TQueryKey: The type of the query key

Example: Full Generic Specification

Query Key Types

Query keys can be strongly typed for type safety:

Extract Query Key Type

Use the queryKey property for type inference:

Query Options Type Safety

Use queryOptions helper for perfect type inference:
queries.ts
The queryOptions helper provides type safety across useQuery, queryClient.fetchQuery, and queryClient.prefetchQuery without repeating type annotations.

Defined Initial Data

When providing initialData, the result type changes:

Mutation Types

useMutation accepts four generic type parameters:
  • TData: The type returned by the mutation function
  • TError: The type of errors
  • TVariables: The type of variables passed to mutate
  • TContext: The type of context used in optimistic updates

Typed Mutations

Infinite Query Types

useInfiniteQuery requires specific generic types:

Infinite Query Options Helper

Use infiniteQueryOptions for type-safe infinite queries:

Query Client Types

Type the QueryClient for custom configurations:

Type-Safe Query Filters

Use filters with proper typing:

Reactive Type Utilities

Vue Query provides type utilities for Vue reactivity:

Shallow Refs

Use shallow option for non-reactive data:
With shallow: true, nested property changes won’t trigger reactivity. Use this only for large datasets where deep reactivity isn’t needed.

Custom Error Types

Define a custom error type for your application:

Type Guards

Create type guards for safer data access:

Strict Null Checks

Vue Query works best with TypeScript’s strict mode enabled:
tsconfig.json
Enable strict mode in TypeScript for the best type safety with Vue Query. This catches potential undefined access at compile time.

Next Steps

DevTools

Debug type-safe queries

API Reference

Full API documentation

Examples

TypeScript examples

Quick Start

Basic usage guide