How to fix TypeScript errors when using Vuex mapGetters?
Asked Answered
P

3

10

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

Predikant answered 28/1, 2018 at 5:51 Comment(5)
You can use fake this parameter: minimizerIconClass(this: ComponentTypeHere). (It exists only at compile time and stripped out during compilation)Prima
What's an example of what ComponentTypeHere would be? (sorry, pretty new to TypeScript)Predikant
It could be just { navCollapsed: boolean } in this specific example. (Need more info, not sure where navCollapsed comes from)Prima
navCollapsed is being injected by mapGetters().Predikant
@Predikant Did you find a way to solve this?Fixing
R
4

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.

Raynard answered 21/9, 2018 at 15:10 Comment(1)
Hello, can you give a full implementation of this solution ? I don't figure out the definition of TMethods, TComputed, TData and TProps.Guidon
N
3

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.

Newly answered 28/1, 2018 at 17:10 Comment(0)
V
0

In my case the mapGetters was outside of the computed. Putting it in there solved the error.

Vitta answered 26/11, 2022 at 23:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.