Skip to main content
Svelte Query is built with TypeScript and provides excellent type safety out of the box. This guide covers how to leverage TypeScript for maximum type inference and safety.

Type Inference

Svelte Query automatically infers types from your query and mutation functions:
The return type of your queryFn determines the type of query.data. TypeScript will automatically infer this type throughout your component.

Typing Queries

Basic Query Types

Explicitly type your queries using generics:

With Data Transformation

When using select to transform data, specify both the source and result types:

Typing Mutations

Basic Mutation Types

With Context for Optimistic Updates

Typing Infinite Queries

Query Options Helper

The queryOptions helper provides excellent type inference:
Using queryOptions provides better type inference than inline options and makes queries reusable across components.

Typing the Query Client

Defined Queries

Use DefinedCreateQueryResult when you know data will always be available (e.g., with initialData):
Or use function overloads:

Type-Safe Query Keys

Create type-safe query key factories:

Custom Error Types

Define custom error types for better error handling:

Accessor Type

Svelte Query uses the Accessor type for reactive options:
This allows the query to track dependencies and refetch when they change:

Result Types

All result types are exported for use in your code:

Generic Components

Create reusable components with generic types:
QueryWrapper.svelte
Usage:

Best Practices

1

Always type your data

Define interfaces for your API responses:
2

Use queryOptions for reusability

Create reusable query definitions:
3

Type your error handling

Use custom error types for better error handling:
4

Use const assertions for query keys

Make query keys readonly:

TypeScript Configuration

Recommended tsconfig.json settings for Svelte Query:
tsconfig.json
Enable strict and strictNullChecks for maximum type safety. This ensures you handle undefined data properly.

Troubleshooting

Type errors with query data

If you get errors like “Object is possibly undefined”:

Inference not working

If types aren’t being inferred correctly:

Next Steps

1

DevTools

Install the Svelte Query DevTools for debugging.DevTools Setup →
2

Advanced Patterns

Learn advanced TypeScript patterns for queries.Advanced Guides →