Heim  >  Fragen und Antworten  >  Hauptteil

Initialisierung des Zustands in Pinia mit Typescript

Ich habe einige Probleme beim Hinzufügen von Typoskript zum Pinia-Store und habe mich gefragt, ob HPW das beheben kann. Dieses Projekt verwendet Pinia:^2.0.16 und Vue:3.2.37

Das ist der Fehler:

Typ „{}“ fehlt die folgenden Eigenschaften im Typ „Order“: id, user_id, gesamt, Benutzer, Produkt

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

Model/ShoppingCart.ts

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

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

model/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[]
}

model/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
}

model/category.ts

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

model/User.ts

import type { Order } from './Order'

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

Ich erhalte einen Tippfehler in der Eigenschaft order von InitialState:

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

Wie kann dieser Fehler behoben werden? Danke

P粉727531237P粉727531237314 Tage vor461

Antworte allen(1)Ich werde antworten

  • P粉283559033

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

    因此,为了得到上面评论中提到的正确答案,该对象应该为 null。

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

    因此

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

    Antwort
    0
  • StornierenAntwort