Vuex Module Decorator模块内访问store出现TypeScript类型报错如何解决
问题根因
vuex-module-decorators的VuexModule运行时会自动注入store实例,但官方类型定义未公开声明该属性,因此仅会出现类型报错,不影响实际功能。
解决方案
方案1:全局扩展VuexModule类型(推荐,一次性生效)
在项目的类型声明目录(通常是@types目录或者shims-vue.d.ts等已被tsconfig识别的声明文件)中添加如下声明:
import { Store } from "vuex"; declare module "vuex-module-decorators" { interface VuexModule<S = any, R = any> { // 全局为所有VuexModule添加store属性类型 store: Store<R>; } }
添加后重启IDE,所有继承VuexModule的模块都可以直接识别this.store的类型,不需要修改原有业务代码。
方案2:封装公共基础模块类
如果不想全局修改第三方库的类型,可以自己封装一个基础模块类,所有业务模块继承该类即可:
// store/base.ts import { Module, VuexModule } from "vuex-module-decorators"; import { Store } from "vuex"; @Module({ namespaced: true, stateFactory: true, preserveState: true, }) export default class BaseModule<S = any, R = any> extends VuexModule<S, R> { // 显式声明store属性类型 store: Store<R>; }
后续业务模块修改继承对象即可:
// store/user.ts、store/basket.ts都改成继承BaseModule import BaseModule from './base' @Module({ name: 'user' }) export default class UserModule extends BaseModule { // 原有代码不变,此时this.store已经有类型 }
临时解决方案(不推荐)
如果不想调整类型定义,也可以在使用时做类型断言跳过类型检查:
const userStore = useUserModule((this as unknown as { store: Store<any> }).store) // 或者更简单的any断言 const userStore = useUserModule((this as any).store)
关于全局this.$store的说明
this.$store是Vue组件实例上的属性,Vuex模块类的this指向的是模块实例本身,不是组件实例,因此不存在该属性,不需要额外实现该属性的适配。
内容的提问来源于stack exchange,提问作者Orbitall
相关产品推荐
相关产品推荐

