Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

typescript - Typing Actions using vuex-composition-helpers in Vue 2

I am trying to learn how to type my actions using vuex-composition-helpers and am having a hard time figuring out how to properly type my actions of a module. To add some context of structure, I am using NuxtJS 2.14.x.

This is my store file:

import Vuex from 'vuex';
import MyModule, { MyModuleState } from './modules/my';

export type RootState = {
  thing: MyModuleState
}

export function createStore() {
  return new Vuex.Store<RootState>({
    modules: {
      MyModule
    }
  })
}

This is my module:

import { ActionTree, GetterTree, Module, MutationTree } from 'vuex';
import { RootState } from '~/store';

const state = () => ({
  count: 0,
  name: 'Test'
})

export type MyModuleState = ReturnType<typeof state>

const actions: ActionTree< MyModuleState, RootState> = {
  printRootState({ rootState }, title: string) {
    console.log(title, rootState)
  }
}

const MyModule: Module<MyModuleState, RootState> = {
  namespaced: false,
  state, 
  actions 
}

export default MyModule;

And then where my problem lies is in this composable... right now I have the type for actions set to <{printRootState: (_: ActionContext<RatingsModuleState, RootState>, title: string) => void }>, but there has to be a better way to infer the type from the action tree?

This is my composable:

import { useNamespacedActions } from 'vuex-composition-helpers';

export const useMyModule = () => {
  //This is ideally where I would like to use something else besides this typing.
  const { printRootState } = useNamespacedActions<{printRootState: (_: ActionContext<RatingsModuleState, RootState>, title: string) => void }>('modules', ['printRootState']);

  return {
    printRootState
  }  
}

If anybody can point me out a better way than using <{printRootState: (_: ActionContext<RatingsModuleState, RootState>, title: string) => void }> in my composable I would be really grateful!

question from:https://stackoverflow.com/questions/66054530/typing-actions-using-vuex-composition-helpers-in-vue-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...