了解です!
では続けて コラム: よくある落とし穴とその回避策「storeの型推論エラー」 を書きます。
Vuex の useStore() に型 (RootState) をつけているはずなのに、
なぜか state.counter.count に型エラー が出たり、
getters['counter/doubleCount'] が any になってしまう ことがあります。
// 型をつけたつもりなのに…
const store = useStore<RootState>();
// でもここでエラーになる
const count = computed(() => store.state.counter.count);
// ❌ Property 'counter' does not exist on type 'RootState'
| 問題点 | 説明 |
|---|---|
RootState の定義ミス |
RootState に counter: CounterState がない |
Vuex の modules と型定義がズレている |
モジュールのキー名と型が合っていない |
useStore() に型を渡し忘れている |
型パラメータが any のままになっている |
RootState に必ず全モジュールを正しく定義する// store/index.ts
import { CounterState } from './modules/counter';
import { UserState } from './modules/user';
export interface RootState {
counter: CounterState;
user: UserState;
}