Rumah  >  Soal Jawab  >  teks badan

Memulakan keadaan dalam pinia menggunakan Typescript

Saya menghadapi beberapa masalah menambah skrip taip ke kedai pinia jadi saya tertanya-tanya hpw boleh saya betulkan ini, projek ini menggunakan pinia:^2.0.16 dan Vue:3.2.37

Ini adalah ralatnya:

Jenis '{}' tiada sifat berikut dalam jenis 'Pesanan': id, id_pengguna, jumlah, pengguna, produk

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/Keranjang Belanja.ts

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

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

model/Tempahan.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/produk.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/kategori.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[]
}

Saya mendapat ralat skrip taip dalam sifat order InitialState:

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

Bagaimana untuk menyelesaikan ralat ini? Terima kasih

P粉727531237P粉727531237314 hari yang lalu464

membalas semua(1)saya akan balas

  • P粉283559033

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

    Jadi, untuk mendapatkan jawapan yang betul seperti yang dinyatakan dalam komen di atas, objek itu harus batal.

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

    Oleh itu

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

    balas
    0
  • Batalbalas