Skip to main content

Overview

TanStack Store is built with TypeScript from the ground up, providing excellent type inference and type safety throughout your application. This guide covers TypeScript patterns, generic types, and best practices for maintaining type safety.

Type Inference

Automatic Type Inference

TanStack Store automatically infers types from initial values:

Derived Store Type Inference

Derived stores automatically infer their return type:

Explicit Type Annotations

When to Use Type Annotations

Use explicit type annotations when:
  • The initial value is null or undefined
  • You want to enforce a specific interface
  • Working with complex or nested types

Type-Safe State Updates

Function Updaters

Function updaters provide the previous state with full type safety:

Direct Value Updates

Direct value updates are also type-checked:

Generic Types and Atoms

Generic Atom Creation

Create reusable atom factories with generics:

Constrained Generics

Use type constraints for more specific generic types:

Working with Union Types

Discriminated Unions

Use discriminated unions for type-safe state machines:

Type Safety with Subscriptions

Typed Observers

Subscriptions receive properly typed values:

Advanced Type Patterns

Readonly vs Mutable Stores

TanStack Store distinguishes between mutable and readonly stores at the type level:

Type Guards for Complex States

Create type guards for complex state shapes:

Mapped Types for Store Collections

Create type-safe collections of stores:

NoInfer for Improved Type Inference

TanStack Store uses TypeScript’s NoInfer utility type internally to prevent unintended type inference:
This pattern ensures that:
  • Generic types are inferred correctly
  • Function parameters don’t widen the inferred type
  • Return types take precedence in type inference

Type Testing

Test your types using TypeScript’s type checking:

Best Practices

Let TypeScript infer types from your initial values. This reduces boilerplate and keeps your code maintainable:
Use explicit type annotations for complex interfaces or when the initial value doesn’t fully represent the type:
Leverage TypeScript’s discriminated unions for type-safe state transitions:
Use type guards to narrow types and improve type safety:

Common Type Errors and Solutions

Error: Type is not assignable

Error: Property does not exist on type

Next Steps