Vue3+Vuex中computed调用getter报TS2339错误求解决
解决Vue3 + Vuex4中mapGetters映射属性TS2339错误的方案
方案1:调整computed属性顺序
TypeScript会按对象属性定义顺序解析类型,把mapGetters展开放在自定义computed属性前,让TypeScript先识别到映射的dictionary属性:
computed: { ...mapGetters({ dictionary: 'learning/dictionary' }), shuffledDictionary () { return _.shuffle(this.dictionary) } },
方案2:扩展组件全局类型
通过声明文件扩展Vue组件的自定义属性类型,让TypeScript感知到dictionary的存在:
- 在项目
src/types目录下创建/修改vue.d.ts:
import type { Store } from 'vuex' // 导入你的根状态类型,路径根据项目实际调整 import type { RootState } from '@/store' // 定义dictionary的实际类型,替换为你的字典项结构 type DictionaryType = Array<{ id: number; title: string }> declare module '@vue/runtime-core' { interface ComponentCustomProperties { $store: Store<RootState> dictionary: DictionaryType } }
- 确保
tsconfig.json包含该声明文件路径:
{ "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.vue"] }
方案3:改用Vuex组合式API(推荐)
Vue3组合式写法的类型支持更完善,避免map辅助函数的类型问题:
import { useStore } from 'vuex' import { computed } from 'vue' import _ from 'lodash' export default { setup() { const store = useStore() const dictionary = computed(() => store.getters['learning/dictionary']) const shuffledDictionary = computed(() => _.shuffle(dictionary.value)) return { dictionary, shuffledDictionary } } }
内容的提问来源于stack exchange,提问作者Denis Stephanov
相关产品推荐
相关产品推荐

