Reputation: 27713
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()
.
Upvotes: 10
Views: 9422
Reputation: 158
In my case the mapGetters was outside of the computed. Putting it in there solved the error.
Upvotes: 0
Reputation: 430
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.
Upvotes: 4
Reputation: 7779
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.
Upvotes: 3