Search code examples
typescriptvue.jsvuex

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.


Solution

  • 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;
    },