Vuex store type with Typescript

2019-06-17 08:25发布

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条回答
我只想做你的唯一
2楼-- · 2019-06-17 09:28

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";.

查看更多
登录 后发表回答