Response
Writing a standalone Pinia store file for a shopping cart with typed state, add/remove actions, and a total getter.
I don't have permission to write files in this session, so here's the complete store printed directly:
```typescript
// stores/cart.ts
import { defineStore } from 'pinia'
export interface CartItem {
id: string
name: string
price: number
quantity: number
}
interface CartState {
items: CartItem[]
}
export const useCartStore = defineStore('cart', {
state: (): CartState => ({
items: [],
}),
getters: {
total: (state): number =>
state.items.reduce((sum, item) => sum + item.price * item.quantity, 0),
itemCount: (state): number =>
state.items.reduce((sum, item) => sum + item.quantity, 0),
},
actions: {
add(item: Omit<CartItem, 'quantity'>, quantity = 1) {
const existing = this.items.find((i) => i.id === item.id)
if (existing) {
existing.quantity += quantity
} else {
this.items.push({ ...item, quantity })
}
},
remove(id: string) {
const index = this.items.findIndex((i) => i.id === id)
if (index !== -1) {
this.items.splice(index, 1)
}
},
clear() {
this.items = []
},
},
})
```
Uses the options-style `defineStore` (still fully TypeScript/Composition-API-compatible in consuming components via `useCartStore()`). `add` merges quantities for duplicate IDs, `remove` deletes by ID, and `total` sums `price * quantity` across items. Let me know if you'd like the composition-style (`defineStore` with `ref`/`computed`) version instead, or if you want me to write it to disk once you grant file-write permission.