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

Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code: import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Co ...

Looking to seamlessly integrate a CommonJS library into your ES Module project while maintaining TypeScript compatibility?

I am interested in creating a project with Typescript. The project is built on top of the Typescript compiler, so I am utilizing Typescript as a library, which I believe is a CommonJS library. Although the project is designed to run on Node (not in the bro ...

Creating a Rectangular Trapezoid Shape with CSS - Eliminating Unnecessary Spacing

I'm trying to create a trapezoid button using CSS. Here is the intended look: However, my current implementation looks like this: The button appears fine but there seems to be some excess space below it. It's almost like an unwanted margin, ev ...

Tips on rotating a material-ui icon

Having trouble rotating a material-ui icon using the CSS animation property. Can anyone assist in identifying what may be causing the issue? Link to example code sandbox I'm looking for a continuously rotating icon. ...

In TypeScript, vertical bars and null are commonly used for type unions

Greetings! I am just starting to learn JavaScript and TypeScript I have a question about the code snippet below What does the pipe symbol (|) signify? Also, why is null = null being used here? let element: HTMLElement | null = null; ...

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Vue-Router implementation utilizing the onReady() method

As a newcomer to Vue, I'm eager to learn about when the onReady() function will be triggered. The explanation in the Vue Router documentation states: This method queues a callback to be called when the router has completed the initial navigation, w ...

Display a transparent icon in a v-text-field to trigger a tooltip with v-tooltip in Vuetify

I am looking to add a tooltip for the clear icon in the v-text-field. Can you provide instructions on how to accomplish this? <v-text-field ref="newSearchField" v-model="text" class=&qu ...

Is there a way to restrict an array to only accept distinct string literals?

export interface IGUser { biography: string; id: string; ig_id: string; followers_count: number; follows_count: number; media_count: number; name: string; profile_picture_url: string; shopping_product_tag_eligibility: boolean; username: ...

What is the correct way to wrap an http.get in TypeScript?

My understanding of Typescript is limited, so I have a basic question related to my web application's frontend. In most http get-requests, I need to include two parameters. To simplify this process, I created a simple wrapper for HttpClient (from "ang ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

"Exploring the process of integrating a new language into the vuejs3-datepicker feature

Hey there, I'm wondering if anyone knows how to integrate a new custom language into vuejs3-datepicker? I checked out the documentation at https://www.npmjs.com/package/vuejs3-datepicker?activeTab=readme, but it seems like you need to add the new lan ...

The parameter 'host: string | undefined; user: string | undefined' does not match the expected type 'string | ConnectionConfig' and cannot be assigned

My attempt to establish a connection to an AWS MySQL database looks like this: const config = { host: process.env.RDS_HOSTNAME, user: process.env.RDS_USERNAME, password: process.env.RDS_PASSWORD, port: 3306, database: process.env.RDS_DB_NAME, } ...

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

Prisma: Utilizing the include option will retrieve exclusively the subobject fields

I created a function to filter the table building and optionally pass a Prisma.BuildingInclude object to return subobjects. async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> { try { const entity = await ...

Retrieving Headers from a POST Response

Currently, I am utilizing http.post to make a call to a .NET Core Web API. One issue I am facing is the need to extract a specific header value from the HTTP response object - specifically, the bearer token. Is there a method that allows me to achieve thi ...

Tips on updating x-label formatting (to display months in words) utilizing morris.js with Angular 5

Snapshot of my Request. I'm looking to alter the xLabel (2018-01 - to - Jan) and I am utilizing morris.js. ...

Issue with Vuex not functioning properly in Nuxt.js

I'm facing an issue with setting the state in Vuex on my Nuxt.js App. It seems to not be working correctly. So, here is how I am trying to set the state using the fetch method: fetch({app, store, route}) { app.$axios.$get(`apps/${route.params ...

What steps can be taken to establish an array type that is limited to predefined values?

I am currently working on defining a type for an array that requires specific values to be present in a certain order at the beginning of the array. type SpecificArray = ('hello'|'goodbye'|string)[] // Current const myArray: SpecificAr ...