Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37

The error message is as follows:

Type '{}' is missing the following properties from type 'Order': id, user_id, total, user, products

import type { ShoppingCart } from '@/Models/ShoppingCart'
import type { Product } from '@/Models/Product'

const initialState : ShoppingCart = {
  products: [],
  cart: [],
  order: {}, // <- here is the typescript error
}

export const useShoppingCart = defineStore('shoppingcart', {
  persist: true,
  state: () => (initialState),
  actions: {
    addToCart(product: Product) {
      ....
    },
    removeFromCart(){
    .....
    },
   ...
   ...
}

Models/ShoppingCart.ts

import type { Order } from './Order'
import type { Product } from './Product'

export interface ShoppingCart {
  products: Product[]
  cart: Product[]
  order: Order
}

Models/Order.ts

import type { User } from './User'
import type { Product } from './Product'
export interface Order {
  id: number
  user_id: number
  total: number
  user: User
  products: Product[]
}

Models/Product.ts

import type { Category } from '@/Models/Category'

export interface Product {
  id: number
  name: string
  slug: string
  description: string
  price: number
  categories: Category[]
  quantity: number
}

Models/Category.ts

import type { Product } from '@/Models/Product'
export interface Category {
  id: number
  name: string
  slug: string
  products?: Product[]
}

Models/User.ts

import type { Order } from './Order'

export interface User {
  id: number
  name: string
  email: string
  orders: Order[]
}

An error is being triggered in the order property of the InitialState:

const initialState : ShoppingCart = {
  products: [],
  cart: [],
  order: {}, // <- here is the typescript error
}

If anyone has insights on resolving this error, I would greatly appreciate it. Thank you.

Answer №1

To achieve the correct answer, as indicated in the previous comments, the object must be set to null.

const initialCartState: ShoppingCart = {
    products: [],
    cart: [],
    order: null,
}

This means that

export interface ShoppingCart {
    products: Product[]
    cart: Product[]
    order: Order | null
}

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

Dynamically created HTML elements have no events attached to them in Angular and jQuery

Utilizing jQuery, I am dynamically generating new elements within an Angular Form that has been constructed using a Template Driven Forms approach. Despite successfully creating the dynamic elements, they do not seem to be assigned events/callbacks due to ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

Using Regular expressions in JavaScript to eliminate content between two HTML comment tags

I am currently dealing with two HTML comments in this format: <!--Delete--> Blah blah blah blah <!--Delete--> I need to remove these comments, along with any characters and newlines. I am utilizing JavaScript and Grunt for this replacement ta ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

Vue.js encountered an error while trying to load the component: either the template or render function is not

Currently I am delving into the realm of Vue.js paired with Laravel by following this series, where the narrator seems to breeze through without encountering any errors. Unfortunately, when I attempted to change the route, a pesky error made an appearance. ...

Can you provide some guidance on accessing HTTP headers while using Promises to make AJAX requests?

Currently, I am working on resolving jQuery ajax requests using bluebird.js and I have found it quite challenging to access the HTTP headers of the request. Here is a snippet of the code I am working with: Promise.resolve($.get(...)).then(function(data){ ...

What is the most effective method for transmitting a zip file as a response in Azure functions with node.js?

With the Azure function app, my goal is to download images from various URLs and store them in a specific folder. I then need to zip these images and send the zip file back as a response. I have successfully achieved this by following these steps: Send ...

Encountering permission issues while trying to install npm on a Mac M

I've exhausted all options and only scratching the surface of my efforts. Is there anyone who can provide assistance? I substituted my name with 'a', that's the only modification in the error code. a@Air-von-A kanban % npm install npm E ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...

React array fails to update upon modification

Hey there! I've created a component that takes an array of strings, combines them, and then renders a typing animation by wrapping each character in a span tag with toggling opacity from 0 to 1. I noticed an issue when switching the order of displaye ...

The instantiation of the cloudinary module failed because of an error with the injector

I am currently developing a MEAN application based on the template provided by Linnovate. You can find the template at https://github.com/linnovate/mean My goal is to integrate a module called Cloudinary into my application. To achieve this, I followed th ...

How can I prevent the <br/> tag from being included on every new line when exporting data to PDF in jQuery Datatable?

I am currently working with a datatable that contains a large amount of data. Within this table, I have included 2 buttons for exporting the data in PDF and CSV formats. One of the columns within my table contains a comma-separated string, and when I expor ...

How to Extract Calendar Week Numbers in React from a Specific Month

Is there anyone who can assist me in calculating the week numbers for a specific month? For instance, July is expected to have week numbers 26, 27, 28, 29, and 30. How can I accomplish this task and store the results in an array? Currently, I am only abl ...

Finding the main directory in JavaScript: a step-by-step guide

My website uses mod_rewrite to reformat the URLs like this: The issue arises when making AJAX calls to a file: I want to access login.php from the root without specifying the full URL or using the "../" method due to varying folder levels. So, I need a ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

Why do all the cards suddenly come to life when I press the activate button on just one card?

Whenever I try to activate a specific card by clicking the active button, all the cards end up getting activated. I have used the className variable and manually set it to "card mb-3 border-3". My intention is for the className to change when clicking th ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

Errors occur when trying to utilize an enum as a generic type in Typescript that are not compatible

Take a look at the code snippet provided. The concept here is that I have different provider implementations that extend a base provider. Each provider requires a settings object that is an extension of a base settings object. Additionally, each provider c ...

The problem of parameter being NULL in a post request in a .Net Core 3.0 Angular application

This is my first venture into the world of .Net Core Angular projects, so I apologize if my question appears to be too basic. Despite researching similar issues, I am still unable to resolve my problem, which leads me to believe that I must be making a mis ...