Vuex store type with Typescript

前端 未结 3 1759
暗喜
暗喜 2021-01-11 09:41

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 t

3条回答
  •  感动是毒
    2021-01-11 10:17

    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
    }
    const VueStrong = Vue as VueConstructor;
    
    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;
    },
    

提交回复
热议问题