After setting up a Vue2+Vuex typescript app from scratch using the @vue/cli, I am facing an issue with the type declarations of this.$store.state
within my components.
How can I ensure that references to this.$store
are correctly typed as declared by the Vuex store and its modules? By default, all references resolve to Store<any>
.
In my recent update mentioned in this commit, I modified the default src/store/index.ts
to introduce a message
property in the store...
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
interface RootState {
message: string;
}
const state: RootState = {
message: "olleH",
};
export const store = new Vuex.Store({
state,
mutations: {},
actions: {},
modules: {},
});
In another update described in this commit, I made changes to shims-vue.d.ts
following online guidance to add global typed references to the Vue VM. However, I suspect this approach is for Vue3 only, considering the URL's reference to next.vue...
import type { HelloStore } from "./store";
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
declare module "@vue/runtime-core" {
interface ComponentCustomProperties {
$store: HelloStore;
}
}
Despite these updates, autocompletion support for this.$store.state
still does not show the message
property. There seems to be no specific instructions on how to address this issue for Vue2.
What should be the correct pattern to ensure proper typing for this.$store
in Vue2 components using Vuex3? It's frustrating that even with the latest stable releases, properly typed values cannot be achieved. What might I have overlooked?
If you want to explore further, please refer to the repro at https://github.com/cefn/vuex-store-typing.