Maison  >  Questions et réponses  >  le corps du texte

Initialisation de l'état dans Pinia à l'aide de Typescript

J'ai quelques problèmes pour ajouter du texte au magasin pinia, donc je me demandais si hpw puis-je résoudre ce problème, ce projet utilise pinia :^2.0.16 et Vue:3.2.37

Voici l'erreur :

Le type '{}' manque les propriétés suivantes dans le type 'Order' : id, user_id, total, utilisateur, produit

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(){
    .....
    },
   ...
   ...
}

Modèle/ShoppingCart.ts

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

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

modèle/Commande.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[]
}

modèle/produit.ts

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

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

modèle/catégorie.ts

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

modèle/Utilisateur.ts

import type { Order } from './Order'

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

Je reçois une erreur de saisie dans la propriété order de InitialState :

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

Comment résoudre cette erreur ? Merci

P粉727531237P粉727531237314 Il y a quelques jours463

répondre à tous(1)je répondrai

  • P粉283559033

    P粉2835590332023-12-11 09:14:41

    Donc, pour obtenir la bonne réponse comme mentionné dans le commentaire ci-dessus, l'objet doit être nul.

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

    Par conséquent

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

    répondre
    0
  • Annulerrépondre