Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex store type with Typescript

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.

like image 848
zmbq Avatar asked Nov 04 '18 10:11

zmbq


People also ask

Does Vuex support TypeScript?

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.

What is Namespacing in Vuex?

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.

Is Vuex necessary in vue3?

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.


1 Answers

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;
},
like image 181
user1518267 Avatar answered Sep 24 '22 01:09

user1518267