vuex +打字稿+命名空间模块:访问其他模块状态

时间:2018-10-17 21:23:56

标签: typescript vue.js vuex

我正在将vuex与typescript和命名空间模块一起使用。 我有2个模块:“ UserProfile”和“ Trips”。 一切都在一个模块中进行。

我需要从“旅行”模块的动作内部访问存储在“ UserProfile”模块状态内的当前用户。

据我了解,如果不使用typecirpt,则可以使用rootState [“ profile / user”]。

但是使用打字稿,编译器给我这样的错误:

Element implicitly has an 'any' type because type 'RootState' has no index signature.

这是我在“旅行”模块中采取的措施:

async createTrip({ commit, state, rootState, rootGetters}) {
    const user = rootState["profile/user"];
}

使用vuex +打字稿时,有人知道访问另一个命名空间模块所拥有的状态的正确方法吗?

谢谢。

=====更新=====

目前,我发现的唯一可行的解​​决方案是:

1]对于每个创建返回其整个状态的getter的模块(即“ Profile”模块添加了返回ProfileState类型的getter)

2]通过rootGetters从另一个模块使用该获取器:

 async createTrip({ commit, state, rootState, rootGetters}) {
    const profileState: ProfileState= rootGetters["profile/getState"];
    if(profileState.user === undefined ) return;
    console.log("CurrentUser: " + profileState.user.uid);
}

2 个答案:

答案 0 :(得分:0)

只是一个想法,不能简单地在rootState typedef中添加这些模块吗? 像这样:

{ ...; moduleName?: moduleState;}

甚至:

{ ...; [key: string | number]: any;}

答案 1 :(得分:0)

  

但是使用打字稿,编译器给我这样的错误:

     

Element implicitly has an 'any' type because type 'RootState' has no index signature.

此错误表明您在类型声明中错过了添加定义的步骤:

例如:

export type RootState = {
  //...
  profile?: ProfileState
}

export type RootState = {
  //...
  [k in keyof ModuleStateTypes]?: ModuleStateTypes[k] 
}

Mapped types

相关问题