How to fix TypeScript errors when using Vuex mapGetters?
I would recommend using vuex-class for decorators with Typescript.
But if you don't want the extra dependency, I believe using this['navCollapsed']
instead of this.navCollapsed
should resolve the compilation error.
I faced the same problem and did the following:
declare module "vuex" { interface TMapGetters { <TGetters>(getterNames: Array<keyof TGetters>): Partial<TGetters>; } export const mapGetters: TMapGetters;}
Then in my store I define:
interface TGetters { navCollapsed: boolean;}
Now in my component I can do:
type TThis = TGetters & TData & TMethods & TComputed & TProps;export default Vue.extend<TData, TMethods, TComputed, TProps>({ computed: { ...mapGetters<TGetters>([ 'navCollapsed', ], minimizerIconClass(this: TThis): string { return `fa${this.navCollapsed ? '' : 'r'} fa-window-maximize`; } }}
Far from perfect, but it will detect typos in the array passed to mapGetters
and it will allow you to use your (correctly typed) getter on this
.
However, TypeScript will not know whether you actually did map the getter in question or not.