我在将 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
}
请问如何解决这个错误?谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
因此,为了得到上面评论中提到的正确答案,该对象应该为 null。
const initialState : ShoppingCart = { products: [], cart: [], order: null, }因此
export interface ShoppingCart { products: Product[] cart: Product[] order: Order | null }