Through the magic of Typescript, this library makes Vuex as typesafe as currently possible through a slightly new syntax. This library overrides the types that come with Vuex and provides a slightly altered version.
Usage
importVuexfrom'vuex-typescript-interface';
// store = new Vuex.Store like normal
Vue.use(Vuex);// works
newVue({
i18n,
router,
store,
render:h=>h(App)
}).$mount('#app')
Normally you can pass a state to new Vuex.Store<State>. That has very limited use. With this library you can pass an interface like this to Vuex.Store:
interfaceIStore
{
// State (are non-function properties not marked readonly)
lowerName(state,getters,rootState){// talking to rootState is type safe
returnrootState.name.toLowerCase();
}
},
actions:{
asyncclearName({commit}){
commit('setName','',{root:true});// talking to root is type safe
}
}
};
constroot=newVuex.Store<IRoot>({
state:{
name:''
},
mutations:{
setName(state,name){
state.name=name;
}
},
modules:{child}// you could pass objects here like normal
})
Advanced Modules
When you add modules, you add a property to the state of the store. If you add sub modules, you add a property to the state of that module. All of this is accessible and type safe.
// In this example we can use one big interface if we want.
To take advantage of that sweet type safety for mapping you can use createNamespacedHelpers or createHelpers (which is the only code this library adds to your code base, just a few bytes).
You should use createHelpers instead of mapState, mapGetters, mapActions, and mapMutations since propery types cannot be added to them at this time.
// These functions are type safe (require valid state/getter/mutations/actions)