-
-
Save javisperez/b13d02042620ae663f0a1f81b050ca69 to your computer and use it in GitHub Desktop.
import { createStore } from 'vuex'; | |
// The modules to import | |
import auth, { Store as AuthStore, State as AuthState } from './auth'; | |
import counter, { Store as CounterStore, State as CounterState } from './counter'; | |
// A State type with all the submodules | |
type State = { | |
auth: AuthState; | |
counter: CounterState; | |
} | |
// And the store is an extension of all the stores but each store receives its own state | |
export type Store = AuthStore<Pick<State, 'auth'>> & CounterStore<Pick<State, 'counter'>>; | |
const store = createStore({ | |
modules: { | |
auth, | |
counter, | |
}, | |
}); | |
export function useStore() { | |
// This made the trick to me, i dont love it, but i dont know other way to do it. | |
// The compiler kept complaining about it not being compatible with Vuex' store so i casted it to uknnown | |
// and after that re-casted as the Store we just defined. | |
return store as unknown as Store; | |
} | |
export default store; |
@ux-engineer yeah, i think you're right, but sadly i don't really have the TS experience to make a proper fix without including the whole RootState there. I mean, I'm really a TS noob 😬
No worries, we are using community effort here...if this remains to be unresolved, I will open up an issue to Vuex repository and/or write to core team members in Discord channel 😁
Vue 3 and Vue Router 4 (in beta) are written fully in TypeScript, however, Vuex 4 is not. It's TypeScript rewrite is coming up in Vuex 5 later on. But they have been working towards better TS support already with this version 4, which is still in beta.
Here's an issue thread in Vuex repo related to using modules in Vuex 4.0: vuejs/vuex#1833
I just realized VS Code intellisense is not showing type information for the store instance after passing it from useStore
function, when used inside component. Works if imported in .ts
file.
@javisperez its true that this typing problem could be circumvented with type-casting to
unknown
first.However, this double assertion casting via unknown is a way of forcefully casting any type to any other type. After doing so, as far as I understand (and am not a deep expert in TS), there could be something wrong with our store or with the library, which TypeScript might not be recognizing as an error.
So it doesn't seem a correct solution because there seems to be something wrong with typings in the first place.