Vuex store type with Typescript

陌路散爱 提交于 2019-12-23 07:45:50

问题


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.


回答1:


Unfortunately it is impossible to override the Store<any> type that is defined by the VueX types with a more specific type. The best I could come up with was to add a second field that returns $store but properly typed so you don't have to use casts everywhere or declare it in all your components:

import { Store } from "vuex";

// Type the $tstore properly, which is the same as $store but properly typed.
// Unfortunately you cannot override the Store<any> type.
declare module "vue/types/vue" {
  interface Vue {
    $tstore: Store<State>;
  }
}

// Set $tstore to be a getter that simply returns $store.
Object.defineProperty(Vue.prototype, "$tstore", {
  get: function() {
    return this.$store as Store<State>;
  },
  enumerable: true,
});



回答2:


You could declare a property in your component so typescript will apply typing. I use this for $refs all the time but it works for the $store too. You don't need to do anything with the property apart from marking it with ! operator to tell the transpiler that vue will set the variable for you.

$store!: Store<StoreStateType>;

Another alternative I use is to use the MapState or MapGetters component helpers. They create the properties for you so you can use them in the template. Example:

@Component({
  computed: mapState({
    userFullName: (state: any) => state.user.fullName,
    userEmail: (state: any) => state.user.email
  })
})

Don't forget to import the Store, your vuex state class and any helper you use import { Store, mapState } from "vuex";.



来源:https://stackoverflow.com/questions/53139966/vuex-store-type-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!