0
0
Vueframework~5 mins

Type-safe stores with Pinia in Vue

Choose your learning style9 modes available
Introduction

Type-safe stores help you catch mistakes early by checking your data types. Pinia makes managing app data easier and safer with TypeScript.

You want to share data between different parts of your Vue app safely.
You want to avoid bugs caused by wrong data types in your store.
You are building a medium or large Vue app that needs organized state management.
You want better code completion and error checking in your editor.
You want to keep your app data predictable and easy to maintain.
Syntax
Vue
import { defineStore } from 'pinia'

export const useStore = defineStore('storeId', {
  state: () => ({
    count: 0 as number,
    name: '' as string
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})

Use defineStore to create a store with a unique ID.

Type your state properties using TypeScript for safety.

Examples
A simple counter store with a typed count state and an increment action.
Vue
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0 as number
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})
Using an interface to type the state for better clarity and reuse.
Vue
import { defineStore } from 'pinia'

interface UserState {
  name: string
  age: number
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: '',
    age: 0
  }),
  actions: {
    setName(newName: string) {
      this.name = newName
    }
  }
})
Sample Program

This Vue app uses a type-safe Pinia store to manage a list of todos. Clicking the button adds a new todo safely.

Vue
import { createApp } from 'vue'
import { createPinia, defineStore } from 'pinia'

// Define a type-safe store
export const useTodoStore = defineStore('todo', {
  state: () => ({
    todos: [] as string[]
  }),
  actions: {
    addTodo(todo: string) {
      this.todos.push(todo)
    }
  }
})

// Create Vue app
const app = createApp({
  template: `
    <div>
      <h2>Todos</h2>
      <ul>
        <li v-for="todo in todoStore.todos" :key="todo">{{ todo }}</li>
      </ul>
      <button @click="addSampleTodo">Add Sample Todo</button>
    </div>
  `,
  setup() {
    const todoStore = useTodoStore()
    function addSampleTodo() {
      todoStore.addTodo('Learn Pinia')
    }
    return { todoStore, addSampleTodo }
  }
})

app.use(createPinia())
app.mount('#app')
OutputSuccess
Important Notes

Pinia works well with TypeScript to give you type safety and better editor support.

Always type your state and actions to avoid bugs.

Use interfaces or types to keep your store code clean and reusable.

Summary

Type-safe stores help prevent bugs by checking data types.

Pinia makes it easy to create and use stores in Vue apps.

Typing state and actions improves code quality and developer experience.