Utilizing the String Enum for mapping an interface with an index

Using Typescript, I aim to make use of my string enumeration:

export const enum MutationKeys {
    registerUser = 'registration/REGISTER',
    registerUserCompleted = 'registration/REGISTER_COMPLETED'
}

This allows the string values to impose type-checking restrictions on an object like this:

const mutations: IDictionary<VuexMutation> = {
    ['registration/REGISTER'](state, payload) {
        state.registration = {
            meta: {
                serverValidated: false
            },
            value: payload
        };
    },
    ['registration/REGISTER_COMPLETED'](state) {
        state.registration.meta.serverValidated = true;
    }
};

The IDictionary<VueMutation> interface in the example above enables me to define the value type for the object, while still allowing for any string index.

Answer №1

To implement this functionality, you can utilize the key in construct:

export const enum MutationKeys {
  addUser = 'user/ADD',
  deleteUser = 'user/DELETE'
}

type MutationMap<Payload> = {
  [key in MutationKeys]: Payload
}

const mutations: MutationMap<VuexMutation> = {
  ['user/ADD'](state, payload) {
    state.user = {
      meta: {
        validated: false
      },
      data: payload
    };
  },
  ['user/DELETE'](state) {
    state.user.meta.validated = 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

Encountered an issue while attempting to assign a value to a property that is declared as [key in keyof T]

I am currently working on implementing a function that selects specific properties of an object. Here is the current function: const project = function<T>(object: T, projection: Projection<T>): Partial<T> { throw new Error("not imple ...

Removing punctuation from time duration using Moment.js duration format can be achieved through a simple process

Currently, I am utilizing the moment duration format library to calculate the total duration of time. It is working as expected, but a slight issue arises when the time duration exceeds 4 digits - it automatically adds a comma in the hours section (similar ...

Dynamically assigning values to class properties in Angular with Typescript is a powerful

I am working on a project where I have a class and a JSON object. My goal is to update the properties in the class based on the values in the JSON object, using Angular 9. This is the class: export class Searchdata{ name:boolean=false; age:boolean=fa ...

What is the best way to ensure the website theme remains consistent after a refresh in React?

I am currently enhancing a weather forecast website by incorporating a theme toggler feature. The functionality has been successfully implemented, but I am facing an issue where the selected theme does not persist after reloading the page. Can someone he ...

Form with Material-UI's FreeSolo AutoComplete feature

Visit this Sandbox for more details In the provided SandBox example, Material AutoComplete is being used as a multiple input with free options. The component is expected to return ["term1","term2","term3"] to Formik, and each string should be displayed as ...

Guide on accessing the afterClosed() method / observable in Angular from a Modal Wrapper Service

Currently, I am in the process of teaching myself coding and Angular by developing a personal app. Within my app, I have created a wrapper service for the Angular Material ModalDialog. It's a mix of Angular and AngularJS that I've been working on ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Angular is throwing error TS2322 stating that the type 'string' cannot be assigned to the type '"canvas" while working with ng-particles

My goal is to incorporate particles.js into the home screen component of my project. I have successfully installed "npm install ng-particles" and "npm install tsparticles." However, even after serving and restarting the application, I am unable to resolve ...

Running the `npm start` command in Angular tends to be quite time-consuming

When I use Visual Studio Code to run Angular projects, my laptop seems to take a longer time when running the server through npm start compared to others. Could this delay be related to my PC specifications, or is there something I can do to improve it? ...

Unable to access 'export default class extends Vue' in the template

I've recently started using Vue.js with TypeScript, but I'm having trouble accessing values from outside the class. @Component({ name: 'SidebarItem', components: { SidebarItemLink } }) export default class extends ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Verify the anticipated URL and showcase the real URL

During a functional test, I am attempting to create a "Then" step where the current URL is verified. After researching on SO, it appears that the proper approach is to wait for the URL to match the expected one: Then('The URL contains {string}' ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

Unable to execute the Vite project

I ran into an issue with my Vite project yesterday. I closed it and now that I have reopened it, the 'npm run dev' command is throwing an error. My project is built using Vite with React and TypeScript. Attached is a screenshot of the error mess ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Reactjs-ffsevents does not exist as a function

An error occurred: TypeError: fsevents is not a function. This issue is located in the FSEventsWatcher file at line 162. A new FSEventsWatcher was attempted to be created in jest-haste-map, triggering this error. The watcher creation process involved map ...

What is the best way to refresh a Component upon sending data to the server?

I'm in the process of developing a cross-platform application. I have a TabView Component that needs to update a tab after sending data to the server. During the initialization (ngOnInit) phase, I dynamically set the content of my tab. However, when I ...

Having trouble assigning a value of `undefined` to a TextField state in React hook

I am in need of setting the initial state for a TextField date to be undefined until the user makes a selection, and then allowing the user an easy way to reset the date back to undefined. In the code snippet below, the Reset button effectively resets par ...

Displaying an error message following the dynamic retrieval of the input field's value

How can I display an error message when a specific field with a value of 0 is not filled out in my Angular reactive forms? In my form, I have added a dropdown which is mandatory and I have implemented validators to ensure it is required. The validator work ...

Tips for setting the scroll back to the top when switching between pages in quasar

Whenever a qlist item is clicked by the user, it redirects to another page. However, the scrolled position from the previous page is retained and not set to the top. This means that the user has to manually scroll back to the top to view the contents of th ...