When using typescript in Vex4, using modules, the type is lost if you don’t do something to fix the store in Hooks and then get the state of the submodule.
First, we need to set up some basic things by referring to the ts usage of modules in VUex4.0 and vue3 + vuex4.0 + typescript. One of the weaknesses of this article is that you need to add the Module state type yourself, so let TypeScript get it as well.
Let’s just go to the code
import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore, } from 'vuex'
import UserinfoStore from './user.store'
// Declare type for store state
export interface State extends modulesState{}
type modulesState = {
[key in keyof typeof modules]: Exclude<Exclude<typeof modules[key]['state'].undefined>, () = > any>}// Define the injection key
export const key: InjectionKey<Store<State>> = Symbol(a)const modules = {
UserinfoStore,
}
export const store = createStore<State>({
modules,
})
// define your own 'useStore' combinatorial function
export function useStore () {
return baseUseStore<State>(key)
}
Copy the code
Key in keyof Modules: Exclude
, () => any>
Fetching typeof Modules [key][‘state’] is a problem because state in Module type is officially specified as an associative type. Using it directly doesn’t show anything and requires further processing.
export interfaceModule<S, R> { namespaced? :boolean; state? : S | (() = >S); getters? : GetterTree<S, R>; actions? : ActionTree<S, R>; mutations? : MutationTree<S>; modules? : ModuleTree<R>; }Copy the code
In which state? : S | (() => S); Conversion is S | (() = > S) | undefined, we just need to get generic S type here is ok, you can use advanced type to Exclude the don’t need to type out, first of all, eliminate undefined, The State type of Modules can be obtained by using any method instead of S.