Home  >  Q&A  >  body text

Initializing state in pinia using Typescript

I'm having some issues adding typescript to the pinia store so I was wondering if hpw can I fix this, this project is using pinia:^2.0.16 and Vue:3.2.37

This is an error:

Type '{}' is missing the following properties in type 'Order': id, user_id, total, user, product

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/ShoppingCart.ts

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

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

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

model/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
}

model/category.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[]
}

I'm getting a typescript error in the order property of InitialState:

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

How to solve this error? Thanks

P粉727531237P粉727531237314 days ago458

reply all(1)I'll reply

  • P粉283559033

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

    So, to get the correct answer as mentioned in the comments above, the object should be null.

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

    therefore

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

    reply
    0
  • Cancelreply