What is the proper way to utilize a custom property that has been incorporated into my Pinia stores in a Typescript project?

Currently utilizing Vue 3 alongside Pinia; my api service is utilized for making requests to the api. I have included it as a property to ensure availability across all stores:

In my main.ts file:

import { http } from "@/services/http";

const store = createPinia();
store.use(({ store }) => {
  store.http = http
})

Although everything appears to function correctly, TypeScript flags an error indicating that the http property does not exist.

Within stores/system.ts:

export const useSystemStore = defineStore("system", {
  state: () => ({
    data: <SystemResponse>{
      ...
    }
  }),
  actions: {
    connect() {
      this.http.get("system")  // <-- Property 'http' does not exist on type '{ connect(...
        .then((response) => {
       ...
       ...

How can I resolve this issue and make TypeScript recognize it?

While scouring through Pinia's documentation, unfortunately, the solution for addressing this problem eluded me.

Answer №1

According to the documentation, it is necessary to define your new property on the PiniaCustomProperties interface.

In this scenario, you will need to create a file named pinia.d.ts and include the module declaration as shown below:

import 'pinia';

declare module 'pinia' {
  export interface PiniaCustomProperties {
    http: YourHttpTypeGoesHere;
  }
}

By following these steps, TypeScript errors should be resolved.

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

Oops! An unhandled promise error occurred when trying to fetch a URL with a status of 0. The response received has a status code of

I keep encountering an error whenever I try to hit a post request URL: Error: Uncaught (in promise): Response with status: 0 for URL: null at c (http://localhost:8100/build/polyfills.js:3:19752) at c (http://localhost:8100/build/polyfills.js:3:1 ...

Filtering an array of objects based on another array of objects in Angular2 through the use of pipes

I'm having trouble understanding how to use the angular pipe to filter an array of objects based on another array of objects. Currently, I have a pipe that filters based on a single argument. I am working with two arrays, array1 and array2, both cont ...

Mocking multiple services and their constructors in an Angular 2 TypeScript Jasmine test component

I've got this login component code snippet that I need help testing in Angular. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@ ...

Unable to run `create-react-app` with the `--template typescript` option

Every time I try to execute the following command: npx create-react-app my-app --template typescript only a JavaScript project is created, without any .tsx files. After consulting the CRA's TypeScript guide, it appears that the command requires Node ...

How can I access other properties of the createMuiTheme function within the theme.ts file in Material UI?

When including a theme in the filename.style.ts file like this: import theme from 'common/theme'; I can access various properties, such as: theme.breakpoints.down('md') I am attempting to reference the same property within the theme ...

The TypeScript error ts2322 occurs when using a generic constraint that involves keyof T and a

Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo. const _idKey = Symbol('_idKey') const _sortKey = Symbol('_sortKey') export interface BaseSt ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

Tips on continuously making calls to a backend API until receiving a successful response with status code 200

While working on my Angular project, I have encountered a situation where I need to make calls to a backend API. If the response is not 200 OK, I have to keep calling the API every 30 seconds until I receive a successful response. In Angular, I usually ca ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

Troubleshooting image display issues in Vue components when using Vite with Laravel

Previously, all of the images were displaying correctly until I started using Laravel with Vite. Now, the images from inside Vue components have stopped working and I can't seem to find a solution for this issue. The images are stored in Laravel with ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...

Dividing an array into categories with typescript/javascript

Here is the initial structure I have: products = [ { 'id': 1 'name: 'test' }, { 'id': 2 'name: 'test' }, { 'id' ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

The NextJS application briefly displays a restricted route component

I need to ensure that all routes containing 'dashboard' in the URL are protected globally. Currently, when I enter '/dashboard', the components display for about a second before redirecting to /login Is there a way to redirect users to ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Securing important code sections in Node/Express using Typescript: A guide

I'm fairly new to the world of JavaScript/Typescript/Node/Express, and as I've been researching, it seems there isn't a universally accepted method for locking critical sections of code in a Node/Express application. I've come across a ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...