When working in a Typescript Vue2 component, accessing the $store through typing this.$store

After setting up a Vue2+Vuex typescript app from scratch using the @vue/cli, I am facing an issue with the type declarations of this.$store.state within my components.

How can I ensure that references to this.$store are correctly typed as declared by the Vuex store and its modules? By default, all references resolve to Store<any>.

In my recent update mentioned in this commit, I modified the default src/store/index.ts to introduce a message property in the store...

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

interface RootState {
  message: string;
}

const state: RootState = {
  message: "olleH",
};

export const store = new Vuex.Store({
  state,
  mutations: {},
  actions: {},
  modules: {},
});

In another update described in this commit, I made changes to shims-vue.d.ts following online guidance to add global typed references to the Vue VM. However, I suspect this approach is for Vue3 only, considering the URL's reference to next.vue...

import type { HelloStore } from "./store";

declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $store: HelloStore;
  }
}

Despite these updates, autocompletion support for this.$store.state still does not show the message property. There seems to be no specific instructions on how to address this issue for Vue2.

What should be the correct pattern to ensure proper typing for this.$store in Vue2 components using Vuex3? It's frustrating that even with the latest stable releases, properly typed values cannot be achieved. What might I have overlooked?

If you want to explore further, please refer to the repro at https://github.com/cefn/vuex-store-typing.

Answer №1

The name of the module you are using for type augmentation is specifically designed for Vue 3 only (the syntax differs slightly in Vue 2). It's important to note that support for augmenting types with the $store instance property was introduced in Vuex 4 as noted in this issue, which means it is not available in Vuex 3.

However, an alternative approach would be to utilize the exported store instance (already defined as HelloStore) instead of accessing it through this.$store. These two references point to the same instance:

import store from '@/store' // store type is HelloStore

export default {
  mounted() {
    console.log(this.$store === store) // => true
  }
}

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

Elements constrained by themselves in a rest parameter with generic types

When using Typescript, it is possible to infer tuple types for generic rest parameters that are constrained by an array type. However, in my specific case, this functionality does not seem to work as expected. I am attempting to pass a series of pairs co ...

Enhance your Vue.js experience with an improved method for monitoring values

My setup involves Vue CLI 3.11 (based on Node.js 12.10) and Google Chrome. I am trying to create a syntax that can bypass the watch function under specific conditions. However, I am struggling because Vue.js handles value changes differently compared to J ...

Enhance data table by displaying a set number of rows that do not completely fill the table's height

I'm currently attempting to implement a v-data-table with fixed header and footer. However, I've encountered an issue where if I set the table height to be larger than the row height, the table takes on the defined height and the footer ends up b ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Trouble with Excel Office Script setInterval functionality

Trying to automatically recalculate an Excel worksheet every second using Office Script. Unfortunately, my initial approach did not succeed. function sendUpdate(sheet: ExcelScript.Worksheet) { console.log('hi'); sheet.calculate(true); } func ...

Filtering the array of objects in the Vuex state resulted in an empty array being

I am working with a state that fetches data from https://jsonplaceholder.typicode.com/todos/. My goal is to filter this data based on the status completed:true or completed:false. Below is the method I am using to filter the array: filterByStatus(status ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Organizing data in TypeScript

Is there a way to alphabetically sort this list of objects by name using TypeScript? "[{name:"Prasanna",age:"22",sex:"Male",Designation:"System Engineer",Location:"Chennai"}, {name:"Nithya",age:"21",sex:"Female",Designation:"System Engineer",Location ...

Is there a way to implement several filters on an array simultaneously?

Is it possible to filter an array based on both the input text from the "searchTerm" state and the selected option from the dropdown menu? I am currently using react-select for the dropdown functionality. const Positions = ({ positions }: dataProps) => ...

Removing the brackets from a nested array: A simple guide

Hello everyone! I need some assistance with removing the brackets and separating each data from a nested array. Here is the code I am working with: <template> <v-data-table :headers="headers" :items="teams" > ...

Tips for implementing the quill-image-drop-module with Vue 3

I am currently utilizing the vueup/vue-quill package for Vue 3 and I would like to incorporate the kensnyder/quill-image-drop-module. This is the snippet of my code: Main.js import { QuillEditor } from '@vueup/vue-quill'; import '@vueup/vu ...

The absence of multiple lines on the x-axis in the linear chart was noticeable

Currently, I am facing an issue with loading a single axis line chart on my Dashboard.vue. The functionality involves users selecting a 'year' and a 'loan_type' from dropdown menus, after which the chart should display a 12-month record ...

Problem encountered during NextJS build: ReferenceError - 'window' is undefined

While I am in the process of developing my app, I have encountered a perplexing issue with a ReferenceError: window is not defined. This error seems to be happening even though I am utilizing 'use client' "use client"; import React, { u ...

Difficulty Resolving Parameter Resolution in Angular 5 Shared Library Module ([object Object], ?, ?)

I'm facing an issue while attempting to integrate a custom shared component library into my Angular application, which has been upgraded from Angular 5 to Angular 4. Unfortunately, I am unable to resolve the problem at hand. The error message I&apos ...

Storing polymorphic relationships efficiently with Laravel forms

I currently have a model called notes, which includes a polymorphic 'noteable' method that can be used by various models, such as Customers, Staff, and Users. I am seeking the most efficient solution for dynamically creating notes for these mode ...

What is the process of retrieving the return value after creating data in Firestore

I have been experimenting with creating data using firestore in the following manner: createData({state}) { return db.collection('items').add({ title: state.title, ingredients: state.ingredients, creat ...

The Radio Button's value appears in a distinct way on Ionic Angular

I am currently working with the Ionic framework and I am trying to display data values on radio buttons. However, I am facing difficulties in retrieving the correct value and setting it appropriately. index.html <td> <label>{{learn ...

Exploring the Synergy of Nestjs Dependency Injection with Domain-Driven Design and Clean Architecture

I am currently exploring Nestjs and experimenting with implementing a clean-architecture structure. I would appreciate validation of my approach as I am unsure if it is the most effective way to do so. Please note that the example provided is somewhat pseu ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...