我在添加typescript到pinia store时遇到了一些问题,所以我想知道如何解决这个问题,这个项目使用的是pinia:^2.0.16和Vue:3.2.37
错误:
类型"{}"缺少类型"Order"的以下属性:User_id, total, user, products
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[]
}
模型/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
}
模型/Category.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:
const initialState : ShoppingCart = {
products: [],
cart: [],
order: {}, // <- here is the typescript error
}
我该如何解决这个错误?谢谢你
因此,如上所述的正确答案,该对象应该为null。
const initialState : ShoppingCart = {
products: [],
cart: [],
order: null,
}
因此和
export interface ShoppingCart {
products: Product[]
cart: Product[]
order: Order | null
}