使用 Typescript 初始化 pinia 中的狀態
P粉727531237
P粉727531237 2023-12-10 21:55:29
0
1
455

我在將 typescript 添加到 pinia 商店時遇到一些問題,所以我想知道 hpw 我可以解決這個問題嗎,這個項目正在使用 pinia:^2.0.16 和 Vue:3.2.37

這是錯誤:

類型「{}」缺少類型「Order」中的以下屬性:id, user_id、總計、使用者、產品

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

模型/ShoppingCart.ts

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

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

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

模型/產品.ts

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

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

模型/類別.ts

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

模型/User.ts

import type { Order } from './Order'

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

我在 InitialStateorder 屬性中收到打字稿錯誤:

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

請問如何解決這個錯誤?謝謝

P粉727531237
P粉727531237

全部回覆(1)
P粉283559033

因此,為了得到上面評論中提到的正確答案,該物件應該為 null。

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

因此

export interface ShoppingCart {
    products: Product[]
    cart: Product[]
    order: Order | null
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!