When using mapGetters, TypeScript has no visibility into what the getters being bound to the Vue component, so it throws errors. Example:
import Vue from 'vue';
import { mapActions, mapGetters } from 'vuex';
export default Vue.extend({
computed: {
...mapGetters('ui', ['navCollapsed']),
minimizerIconClass(): string {
return `fa${this.navCollapsed ? '' : 'r'} fa-window-maximize`;
},
},
TypeScript is yelling about this.navCollapsed:
TS2339: Property 'navCollapsed' does not exist on type 'CombinedVueInstance<Vue, {}, { openMobileMenu(): void; }, { minimizerIconClass: string; }, Readon...'.
How do I fix this? The only workaround I can come up with is to not use mapGetters().
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With