Skip to content

Instantly share code, notes, and snippets.

@javisperez
Created August 11, 2020 15:13
Show Gist options
  • Save javisperez/b13d02042620ae663f0a1f81b050ca69 to your computer and use it in GitHub Desktop.
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
Copy link

ux-engineer commented Sep 26, 2020

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.

@ux-engineer
Copy link

Here's an issue thread in Vuex repo related to using modules in Vuex 4.0: vuejs/vuex#1833

@ux-engineer
Copy link

ux-engineer commented Sep 27, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment