Enhance your Vuex action types in Typescript by adding new actions or extending existing

I'm new to Typescript and I'm exploring ways to add specific type structure to all Actions declared in Vue store without repeating them in every Vuex module file.

For instance, instead of manually defining types for each action in every store file, it can be done as shown below:

// Global interface declaration.
interface ReturnObject {
   status: boolean;
   msg: string;
}

export default new Vuex.Store({
   actions: {
      // Each action needs to follow this pattern.
      exampleAction: async (context, payload): Promise<ReturnObject> => {
         return { status: true, msg: 'Hello World!' }
      },
   },
   modules: {
      // Also applied to actions in module files.
   }
})

However, the goal is to achieve the following approach:

export default new Vuex.Store({
   actions: {
      // Types are automatically inferred.
      async exampleAction(context, payload) {
         return {status: true, msg: 'Hello World!'}
      }
   },
   modules: {
      // Applied to actions in all module files.
   }
})

Answer №1

It is generally not recommended to modify original global behavior for specific local purposes. Instead of directly modifying it, a better approach would be to use custom helpers to extend the functionality. One possible solution is to create a simple wrapper that extends the original store types:

type CustomActionHandler<S, R> = (this: Store<R>, injectee: ActionContext<S, R>, payload?: any) => ReturnObject | Promise<ReturnObject>;

interface CustomActionTree<S, R> {
  [key: string]: CustomActionHandler;
}

interface CustomModule<S, R> extends Module<S, R> {
  actions?: CustomActionTree<S, R>;
}

export interface CustomModuleTree<R> {
  [key: string]: CustomModule<any, R>;
}

interface CustomStoreOptions<S> extends StoreOptions<S> {
  actions?: CustomActionTree<S, S>;
  modules?: CustomModuleTree<S>;
}

function createCustomStore<S>(options: CustomStoreOptions<S>) {
  return new Store(options);
}

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

When implementing require('devtron').install(), it triggers the error message "Uncaught TypeError: Cannot read property 'BrowserWindow' of undefined" within an Electron application

I'm attempting to install devtron's developer tools from the Electron application developer console. However, I encountered an error when trying to run the install command: > require('devtron').install() Uncaught TypeError: Cannot r ...

Creating an overloaded callable interface using TypeScript

The thread on implementing a callable interface provides some helpful information, but it doesn't fully address my specific query. interface lol { (a: number): (b: number) => string // (a: string): (b: string) => string // overloaded wi ...

Stop data from being submitted on the search form when entered

In my form, there is a search box within the form component. I have created two methods, one for searching and the other for submitting data. Every time I enter something in the search box, both methods are triggered. I used @submit.prevent="saveFormData" ...

Guide to integrating global interfaces into your Nuxt project

Recently diving into the world of Nuxt 3, I've encountered a challenge while exploring TypeScript functionalities. My current goal is to create a versatile NavBar featuring multiple buttons with unique links. To achieve this, I aimed to establish an ...

"Caution: The `className` property did not align" when configuring a theme provider within Next.js

I'm currently working on developing a theme provider using the Context API to manage the application's theme, which is applied as a className on the body element. The implementation of the context is quite straightforward. When initializing the ...

What is the process for transforming a Typescript source file into JavaScript?

I have a basic HTML file with a script source set to index.ts. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge ...

Leveraging the power of CSS calc() in combination with TailwindCSS styles and JavaScript

Can you explain why applying styles with TailwindCSS v3 to calculations using JS variables does not work? I'm working on a project using VueJS, and I've noticed that styling works fine when using calc as a string like this: ... <div class=&qu ...

Encountered a problem while trying to inherit from the BrowserWindow class in

I utilized the https://github.com/SimulatedGREG/electron-vue template to craft a vue electron blueprint. Alongside the primary process index.js, I fashioned a file named MainWindow.js which holds the subsequent code: import { BrowserWindow } from 'el ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...

Error message indicating that an image cannot be located within assets folder while using @error in Nuxt

Having an issue with one of the images in my card component not loading due to a (HTTP Status: 403) error. I wanted to replace it with a default image, so after some research, I found out that I can use @error. <div class="card-thumbnail"> ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Combining attributes of objects in an array

Is the title accurate for my task? I have an array structured like this: { "someValue": 1, "moreValue": 1, "parentArray": [ { "id": "2222", "array": [ { "type": "test", "id": "ID-100" }, { ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...

Creating a task management application using AXIOS and VUE for easy data manipulation

I am currently working on a small app to enhance my skills in VUE and Axios. However, I am facing a roadblock when it comes to the update functionality. I am struggling to pass the ID to the form for updating and despite watching numerous tutorial videos ...

Definition of union types in JavaScript using Typescript

Looking for assistance in creating a d.ts file for the union-type library found at https://github.com/paldepind/union-type Consider the following union type: let Maybe = Type({ Nothing: [] , Just: [Number] }) I am interested in setting up compi ...

Unable to display content within .vue file

My Index.vue file includes the following code, however, it is not displaying properly. <div> test </div> <script> export default { // } </script> ...

The variable 'selectedvalue' is being accessed before it has been initialized

I'm currently working on sharing the date between components using BehaviorSubject, but I'm encountering an error in the process. public data = new BehaviorSubject<any>(this.selectedValue); public sharedData = this.data.asObservable(); sele ...

Theme not being rendered properly following the generation of a dynamic component in Angular

I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file a ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...