Blog>
Snippets

Implementing TypeScript with TanStack Ranger

Provide an example of using TanStack Ranger in a TypeScript project, defining types for the application state, and showcasing TypeScript's benefits in ensuring type safety.
import { createState, State } from '@tanstack/ranger';

// Define the application state shape
interface AppState {
  count: number;
  user: {
    name: string;
    age: number;
  };
}

// Create the application state with initial values
const appState: State<AppState> = createState({
  count: 0,
  user: {
    name: 'John Doe',
    age: 30
  }
});
This code snippet demonstrates how to use TanStack Ranger to define and create the application state in a TypeScript project. By leveraging TypeScript interfaces, type safety is ensured for the state structure. `createState` from Ranger is used to initialize the state.
// Access and update the state
appState.count.set(count => count + 1);

// Listen to state changes
cosole.log(`Current count is: ${appState.count.value}`);

appState.user.name.set('Jane Doe');

// Subscribe to user name changes
appState.user.name.subscribe(name => {
  console.log(`User name changed to: ${name}`);
});
This code snippet shows how to update and access parts of the state, and how to listen for changes. The Ranger state management allows for fine-grained updates and subscriptions. TypeScript ensures that any access or update to the state is type safe.