I'm trying to get a Vuex store to be Typescript friendly. I'm building the store as explained here. However, when I access this.$store
from a component, the type is Store<any>
.
I couldn't figure out how to change it so that it defaults to Store<MyState>
without requiring a cast every time.
Vuex provides its typings so you can use TypeScript to write a store definition. You don't need any special TypeScript configuration for Vuex. Please follow Vue's basic TypeScript setup to configure your project.
In the previous Vuex tutorial, we learned that by default, getters, actions, and mutations inside modules are registered under the global namespace, which allows multiple modules to react to the same mutation or action.
Both of these could do the work of Vuex, but they aren't enough to replace Vuex completely. Let's take a look at why Vuex is is still necessary, even in Vue 3. First, Vuex offers advanced debugging capabilities that Vue 3 features does not.
If anyone comes across this - we got around this issue by redefining the type that the constructor returned -
import Vue, { VueConstructor } from 'vue'
import { Store } from 'vuex'
import { RootState } from '@/store/types'
abstract class VueStrongClass extends Vue {
public $store!: Store<RootState>
}
const VueStrong = Vue as VueConstructor<VueStrongClass>;
export default VueStrong;
and then we just
export default VueStrong.extend({
name: 'name',
components: {
componentA,
componentB,
},
which lets us then use typing properly:
methods: {
sessionStarted(): Boolean | undefined {
return this.$store.state.sessionState?.session.started;
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With