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.
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.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:
Don't forget to import the Store, your vuex state class and any helper you use
import { Store, mapState } from "vuex";
.