Create a pinia state by defining it through an interface without the need to manually list out each property

Exploring the implementation of state management (pinia) within a single-page application is my current task. We are utilizing typescript, and I am inquiring about whether there exists a method to define a state based on an interface without needing to retype every individual property within the state. Essentially, instructing the state to align with an interface and automatically initialize with the correct structure.

I have managed to establish a state that adheres to a specific interface structure by using defineStore (which is already quite advantageous), but I am curious if it is feasible to incorporate the concept of a spread operator to circumvent typing out all properties of the interface in the state declaration.

Here's a hypothetical example:

interface ICustomer {
    id: number;
    name: string;
    // Up to 100 more properties and sometimes nested objects based on other interfaces
}

export const useCustomersStore = defineStore<string, ICustomer>('customers', {
    state: () => ({
        ...ICustomer,
    }),
...

Our interfaces tend to be extensive (containing anywhere from 50-100 properties each), and having to retype each property within the state declaration can become quite verbose. The primary challenge seems to be that the state requires a default value for initialization, but repeatedly typing out all properties can lead to clutter. Furthermore, this approach may not be very future-proof as we would need to remember to update the state properties whenever changes are made to the interfaces. Our APIs consistently mirror the exact structure of these interfaces; hence, we also specify the interface for each axios call.

Thank you!

Answer №1

Here is an example of how it can be achieved:

interface IUser {
    userId: number;
    username: string;
    // additional properties and possibly nested objects from other interfaces
}

export const useUserStore = defineStore('users', {
    state: (): IUser => ({

    }),
    ...

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

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...

Tips for reusing a Jest mock for react-router's useHistory

When testing my code, I set up a mock for the useHistory hook from react-router-dom like this: jest.mock("react-router-dom", () => ({ useHistory: () => ({ length: 13, push: jest.fn(), block: jest.fn(), createHref: jest.fn(), go ...

Dynamically generating an Angular component and populating it with data

I am currently working with Angular 7/8 and I have some code that adds a new component dynamically. In the parent component, my .ts file includes the following: PARENT COMPONENT Within the .ts file: @ViewChild(InjectDirective) injectComp: InjectDirect ...

Sharing data between VueJS2 components

I am working on a project where the parent component retrieves a large JSON object from the server. My goal is to parse this data and then pass it down to the child components. The structure of the child components is as follows: <child-comp /> I ...

Adding or removing rows within an array in a hybrid Vue project - a step-by-step guide

Recently, I created a small web application to assist in organizing my project ideas. Check it out here: https://codepen.io/aibrindley/pen/ELXajM Now, I am working on enabling users to add items to the array directly from the interface. It would also be c ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Angular Owl Carousel doesn't slide horizontally, it slides vertically

Within my Angular project, I incorporated an Owl Carousel into the home-component.html file. Here is a snippet of the code: <section> <div class="container"> <h1 class="products-title">New Arrivals</h1> ...

The vue-test-utils setData method is failing to trigger a re-render of the component

Currently, I am utilizing vue-test-utils in conjunction with jest. In my Login Component, I have a router-link being displayed. Additionally, I am passing the router to the component. Within this context, there exists data named 'email', and whe ...

Angular Error: Trying to access a property on an undefined variable

I'm currently having an issue with assigning data from an API to my Angular component file. Whenever I try to assign the data to my object variable, I receive an error stating: "cannot set property of undefined." Below is the relevant code snippet: C ...

Enabling or disabling a button dynamically in Ionic based on a conditional statement

I am looking to dynamically enable or disable buttons based on specific conditions. The data is retrieved from Firebase, and depending on the data, I will either enable or disable the button. For example, if a user passes the First Quiz, I want to enable ...

Issue: The --outFile flag only supports 'amd' and 'system' modules

Encountering an issue while trying to compile an Angular project in Visual Studio Code using ng build and then serving it with ng serve Unfortunately, faced the following error message in both cases: The error 'Only 'amd' and 'syste ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

Derivation of the general function parameter

To provide a solution to this problem, let's consider the example below where a function is used. The function returns the same type that it accepts as the first argument: function sample<U>(argument: (details: U) => U) { return null; } ...

Vuejs - Trouble with Component Rendering on the Screen

I'm currently working on developing a Vue application for monitoring and managing budgets. I have a BudgetItems component that I intend to display in the /budget route. Although all other components and raw HTML are successfully rendering, this specif ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

Does Vuex have a feature similar to mapDispatchToProps in Redux for managing actions and state?

In a child component, I found myself using this.updateData() instead of this.$store.dispatch(), with the updateData function being inherited from its parent component. Does anyone know how to accomplish this? ...

NX combined with Nest.js and TypeORM, further enhanced with Webpack and Migrations

Recently, I embarked on a project using NX (Nest.js + Angular) and set up TypeORM for database configuration. While everything runs smoothly in "serve" mode, I found myself struggling with configuring migrations. In a typical Nest.js project, all files in ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

Scoped variable in Typescript producing a generated Javascript file

I'm currently learning TypeScript through an online course, and I've encountered a problem that seems to be related to a VSCode setting. Whenever I compile app.ts, it generates the app.js file, but I immediately encounter a TypeScript error. It& ...