Vuex中{ dispatch, commit }的TypeScript类型定义及使用方法
解决Vuex Action中替换
any类型的问题 我来帮你搞定这个TypeScript类型提示的问题!你已经找对了方向——从Vuex导入Dispatch和Commit类型是正确的思路,但直接单独使用它们还不够完整,咱们可以用更贴合Vuex Action场景的类型来实现更完善的类型支持。
基础替换方案(快速上手)
如果你只是想先替换掉any,可以直接把参数解构后的类型定义为包含dispatch: Dispatch和commit: Commit的对象:
import { Dispatch, Commit } from 'vuex'; async getUserProfile ({ dispatch, commit }: { dispatch: Dispatch; commit: Commit }) { // 现在dispatch和commit都会有完整的编辑器提示啦 commit('SET_PROFILE', {}); dispatch('fetchUserPosts'); }
更完善的类型方案(推荐)
上面的方案只能覆盖dispatch和commit,但Vuex的Action上下文还包含state、rootState等属性,咱们可以用ActionContext类型来获得更全面的类型支持,步骤如下:
- 定义你的State类型
先为当前模块(或根store)的State创建接口,这样TypeScript能识别状态的结构:
// 定义当前模块的State类型 interface UserModuleState { profile: { name: string; email: string; avatar?: string; } | null; loading: boolean; } // 如果有根store,也要定义根State类型 interface RootState { app: { theme: string; }; }
- 使用
ActionContext定义参数类型
从Vuex导入ActionContext,它接收两个泛型参数:第一个是当前模块的State类型,第二个是根State类型:
import { ActionContext } from 'vuex'; async getUserProfile ({ dispatch, commit, state, rootState }: ActionContext<UserModuleState, RootState>) { // 这里state会自动提示UserModuleState的字段,比如state.loading // rootState也会提示RootState的字段,比如rootState.app.theme state.loading = true; try { const profile = await api.fetchUserProfile(); commit('SET_PROFILE', profile); await dispatch('fetchUserPosts'); } catch (err) { console.error(err); } finally { state.loading = false; } }
这样一来,不仅dispatch和commit有完整的类型提示,连state、rootState这些属性也能获得准确的代码补全,彻底告别any带来的类型模糊问题。
内容的提问来源于stack exchange,提问作者pregmatch
相关产品推荐
相关产品推荐

