我在將 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[] }
我在 InitialState 的 order 屬性中收到打字稿錯誤:
const initialState : ShoppingCart = { products: [], cart: [], order: {}, // <- here is the typescript error }
請問如何解決這個錯誤?謝謝
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 }