How is the correct way to work with Vuex and typescript? How is the correct way to work with Vuex and typescript? vue.js vue.js

How is the correct way to work with Vuex and typescript?


Vuex is perfectly compatible with typescript using these vuex imports:

import {GetterTree, MutationTree, ActionTree} from "vuex"

The example below shows the easiest and most complete way to use vuex in typescript.

Principal store file:

import Vue from 'vue'import Vuex from 'vuex'import { GetterTree, MutationTree, ActionTree } from "vuex"import MySubModule from '@/store/submodule'Vue.use(Vuex)class State {    userId: string | null = null;}const getters = <GetterTree<State, any>>{};const mutations = <MutationTree<State>>{    setUserId(state, payload) {        state.userId = payload;    }};const actions = <ActionTree<State, any>>{    fetchUserId(store) {    }};export default new Vuex.Store({    state: new State(),    mutations: mutations,    actions: actions,    modules: {        subModuleName: MySubModule,        //other submodules    }})

SubModule store file:

import { GetterTree, MutationTree, ActionTree } from "vuex"class State {}const mutations = <MutationTree<State>>{};const actions = <ActionTree<State, any>>{};const MySubModule = {    namespaced: true,    state: new State(),    mutations: mutations,    actions: actions};export default MySubModule;

Hoping to help you !