I've been grappling with how to properly type vuex modules in a Vue 3 TypeScript project. The official documentation doesn't provide much guidance on this topic.
Let's say I have a setup like this:
import { createStore, useStore as baseUseStore, Store } from 'vuex';
import { InjectionKey } from 'vue';
interface FruitState {
apple: boolean,
peach: boolean,
plum: boolean
}
const FruitModule = {
namespaced: true,
state: (): FruitState => ({
apple: true,
peach: false,
plum: true
}),
mutations: {},
action: {}
}
export interface State {
foo: string;
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
modules: {
fruit: fruitModule
},
state: {foo: 'foo'},
mutations: {
changeFoo(state: State, payload: string){
state.foo = payload
}
},
actions: {
setFooToBar({commit}){
commit('changeFoo', 'bar')
}}
})
export function useStoreTyped() {
return baseUseStore(key);
}
... and then later in a component:
const apple = computed(() => store.state.fruit.apple);
However, attempting to access apple throws an error stating:
Property 'fruit' does not exist on type 'State'
If I make the following adjustments:
import { createStore, useStore as baseUseStore, Store } from 'vuex';
import { InjectionKey } from 'vue';
interface FruitState {
apple: boolean,
peach: boolean,
plum: boolean
}
const FruitModule = {
namespaced: true,
state: (): FruitState => ({
apple: true,
peach: false,
plum: true,
}),
mutations: {},
action: {}
}
export interface State {
foo: string;
fruit?: FruitState;
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
modules: {
fruit: fruitModule
},
state: {foo: 'foo'},
mutations: {
changeFoo(state: State, payload: string){
state.foo = payload
}
},
actions: {
setFooToBar({commit}){
commit('changeFoo', 'bar')
}}
})
export function useStoreTyped() {
return baseUseStore(key);
}
After making these changes, the error becomes Object is possibly 'undefined'
To work around this issue, I can use optional chaining like so:
const apple = computed(() => store.state.fruit?.apple);
However, I find this workaround unsatisfactory since I know that fruit.apple is never actually undefined.
Does anyone know the correct way to include a module in your state types for Vuex?