Performance: Type-safe stores with Pinia
This affects the JavaScript bundle size and runtime type checking, impacting page load speed and interaction responsiveness.
import { defineStore } from 'pinia'; import { ref, type Ref } from 'vue'; interface State { count: number; } export const useStore = defineStore('main', () => { const count: Ref<number> = ref(0); function increment() { count.value++; } return { count, increment }; });
import { defineStore } from 'pinia'; export const useStore = defineStore('main', { state: () => ({ count: 0 }), actions: { increment() { this.count++; } } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No type safety, no runtime checks | 0 | 0 | 0 | [OK] Good |
| Runtime type checks in actions | 0 | 0 | 0 | [X] Bad |
| Compile-time type safety with TypeScript | 0 | 0 | 0 | [OK] Good |
type-safe stores with Pinia in a Vue application?count of type number?count should be a number, not string or type.count: 0 correctly sets count as number; as number is unnecessary here.const useCounterStore = defineStore('counter', {
state: () => ({ count: 5 }),
actions: {
increment() { this.count++ }
}
})
const store = useCounterStore()
store.increment()
console.log(store.count)count starts at 5. The increment action increases it by 1.store.increment() changes count from 5 to 6, then logging outputs 6.const useStore = defineStore('main', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count = this.count + 1
},
reset() {
this.count = 'zero'
}
}
})count is a number initialized to 0.reset(), assigning string 'zero' to count breaks type safety, causing error.count causes a type error. -> Option Acount causes a type error. [OK]name (string), age (number), and an action updateProfile that accepts a partial object to update state. Which approach correctly ensures type safety?name: string and age: number sets clear expected types.updateProfile parameterdefineStore and typing updateProfile ensures safe updates.updateProfile parameter as Partial<State>. -> Option AupdateProfile parameter as Partial<State>. [OK]Pass the test and this pattern moves unknown