Blog>
Snippets

Using TanStack Store with TypeScript for Type Safety

Illustrate how to use TanStack Store in conjunction with TypeScript to ensure type safety when defining and mutating application state.
import { defineStore } from '@tanstack/store';

interface Todo {
  id: number;
  text: string;
  done: boolean;
}

// Define the store with initial state
export const todosStore = defineStore({
  id: 'todos',
  initialState: {
    todos: [] as Todo[]
  }
});
This code snippet uses TypeScript to define a Todo interface ensuring type safety for todo objects. It then utilizes TanStack Store's defineStore method to create a todosStore with an initial state adhering to the Todo type.
// Mutate the state with type safety
todosStore.setState((state) => {
  state.todos.push({ id: 1, text: 'Learn TanStack Store', done: false });
});
This code snippet demonstrates mutating the state by pushing a new todo item to the todos array. TypeScript ensures the new todo item matches the Todo interface, providing type safety.