Tips for resolving TypeScript issues with Vuex mapGetters

When utilizing mapGetters, TypeScript lacks insight into the getters linked to the Vue component, leading to error messages. For instance:

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 flagging an issue related to this.navCollapsed:

TS2339: Property 'navCollapsed' does not exist on type 'CombinedVueInstance<Vue, {}, { openMobileMenu(): void; }, { minimizerIconClass: string; }, Readon...'.

How can this be resolved? One possible workaround is to avoid using mapGetters().

Answer №1

If you're looking to streamline your code with Typescript, I suggest giving vuex-class a try for decorators.

Alternatively, if you prefer to avoid additional dependencies, you can solve the compilation error by using this['navCollapsed'] instead of this.navCollapsed.

Answer №2

I encountered a similar issue and resolved it by taking the following steps:

declare module "vuex" {
    interface TMapGetters {
        <TGetters>(getterNames: Array<keyof TGetters>): Partial<TGetters>;
    }

    export const mapGetters: TMapGetters;
}

Subsequently, I defined the following in my store:

interface TGetters {
    navCollapsed: boolean;
}

With this setup in place, I am able to do the following in my component:

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`;
        }
    }
}

While not flawless, this approach helps in detecting errors in the array passed to mapGetters and ensures that you can use your correctly typed getter on this.

It is worth noting that TypeScript may not be aware of whether the getter was actually mapped or not.

Answer №3

I encountered an issue where the mapGetters was located outside of the computed section. However, moving it inside the computed section resolved the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Knexfile Doesn't Utilize TypeScript Paths

When attempting to run a migration, I encountered an issue with Knex. My Knexfile is in Typescript and uses path aliases from tsconfig.json. However, Knex is throwing an error stating Cannot find module '@foo-alias/bar-module'. What adjustments d ...

The Vuex mutation does not execute synchronously and does not resolve as a promise

My vuex mutation doesn't work synchronously as expected. Here is the code: mutations: { computeStatusData(state, status) { if (status.active !== true) { return } const started = new Date(status.startedAt); started.setHour ...

How can I reference a function in a single file component using Vue.js?

Within my Vue.js project, I have crafted a single file component known as Password.vue which comprises two password fields along with their associated validation checks. To begin with, I structure my HTML within the <template></template> tags, ...

Implementing image rendering functionality in Vue.js

So here's what's going on: I developed a horror movie bucket list app for my bootcamp final project. The minimum viable product received positive feedback, and I obtained my certification. However, now that I've graduated, I want to enhance ...

Updating the navigation bar in Node/Angular 2 and displaying the sidebar once the user has logged in

I am facing a challenge with my first project/application built using Angular 2, particularly related to the login functionality. Here is what I expect from the application: Expectations: When I load the login component for the first time, the navbar ...

Can you tell me the Vue 3 counterpart of Vue 2's __vue__?

While exploring the code, I noticed the __vueParentComponent property. It seems like now I need to reference __vueParentComponent.props.x instead of using __vue__.x. Additionally, I am struggling to find a way to access my custom variables that I created ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

Ways to efficiently update the API_BASE_URL in a TypeScript Angular client generated by NSwag

Is it possible to dynamically change the API_BASE_URL set in my TypeScript client generated by NSWAG? I want to be able to utilize the same client with different API_BASE_URLs in separate Angular modules. Is this achievable? Thank you for your assistance. ...

Combining Vitest with FastifyAutoload resulted in a FastifyError: The plugin provided must either be a function or a promise, but instead, an 'object' was received

My application built on Fastify ("fastify": "^4.26.0") operates smoothly under normal conditions with no issues. However, when trying to incorporate unit testing using Vitest, every test fails despite their simplicity. Upon troubleshoot ...

Search functionality in Angular using column-based filtering algorithm

Take a look at my table view below. Each column has its own search function. My current issue is that when I type in one column, the same text appears in other columns as well. To solve this problem, I have implemented the following code: <tr& ...

The router link is unable to redirect to the desired page

neither the static router nor the dynamic router can navigate to the page. Here is the HTML code: <router-link to="/add_peer">Test</router-link> <router-link :to="{path:'/add_peer'}">Test</router-link> ...

Guide to making a tooltip using vue.js

Currently, I am developing a Vue2 application that requires a tooltip with interactive buttons to only appear when text in a textarea is selected. I have been searching for a library similar to the one found at , but specifically for Vue2. Despite an ext ...

Tips for creating an animation for transferring a task between two lists using Vue.js?

Attempting to replicate the moving animation in a Svelte example using Vue.js. Here is my progress so far. Simply click on the todo items to view them. new Vue({ el: "#app", data: { items: [ { id: 1, name: 'John', done: false }, ...

Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so: enum AllDirections { TOP = 'top', BOTTOM = 'bottom', LEFT = 'left', RIGHT = 'right', } However, trying to use variab ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

The flatMap function is not operating as intended in the sequence of function calls

Having difficulty organizing a chain of calls using TypeScript with RxJS observables I am new to RXJS and I am struggling to structure a chain of calls in my TypeScript code. My question is - how can I ensure that this.http.get(''); is only cal ...

Challenges with Vuetify grid system in Nuxt: addressing layout inconsistencies, page rendering problems, and component alignment (+ unexpected background color

Attempting to recreate the layout of a login page like the one found here: Mentor Cruise Login Page. I am aiming for a 1/3 vs 2/3 split with a vertically centered login component. Currently, I am using my default.vue layout to control the visibility of th ...

Error encountered while compiling React application: Module build unsuccessful due to failure in ./node_modules/babel-loader/lib/index.js

Having an issue while trying to compile a React app. After pulling the repo from Github, running yarn install, and then compiling it, I encountered the following error: Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError: {file_ ...

Creating Dynamic Forms in React with Typescript: A Step-by-Step Guide to Adding Form Elements with an onClick Event Handler

I am looking to create a dynamic generation of TextFields and then store their values in an array within the state. Here are my imports: import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button&apos ...

What is the best way to incorporate Firebase into an Angular 2 TypeScript application without relying on AngularFire?

What is the best way to integrate Firebase into an Angular 2 TypeScript application without relying on AngularFire? I have a simple Angular 2 application and I am looking to incorporate Firebase into it. ...