Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix TypeScript errors when using Vuex mapGetters?

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().

like image 523
ffxsam Avatar asked Jan 28 '18 05:01

ffxsam


2 Answers

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.

like image 63
MaximeW Avatar answered Nov 18 '22 01:11

MaximeW


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.

like image 41
AbM Avatar answered Nov 17 '22 23:11

AbM