Type-safe stores with Pinia
📖 Scenario: You are building a simple Vue app to manage a list of tasks. You want to keep the tasks in a central store using Pinia. To avoid mistakes, you will make the store type-safe using TypeScript.
🎯 Goal: Create a Pinia store with TypeScript that holds a list of tasks. Each task has an id (number) and a title (string). Add a getter to count tasks and an action to add a new task.
📋 What You'll Learn
Create a Pinia store named
useTaskStore using defineStoreDefine a TypeScript interface
Task with id: number and title: stringStore state as an array of
Task objects named tasksAdd a getter
taskCount returning the number of tasksAdd an action
addTask that takes a Task and adds it to tasks💡 Why This Matters
🌍 Real World
Type-safe stores help prevent bugs by ensuring data shapes are consistent. This is useful in any Vue app managing shared state.
💼 Career
Many Vue jobs require managing state with Pinia and TypeScript. Knowing how to create type-safe stores is a valuable skill.
Progress0 / 4 steps