Home > database >  How to set up the initial state in pinia using Typescript
How to set up the initial state in pinia using Typescript

Time:11-24

I having some problems when adding typescript to a pinia store, so I would like to know hpw can I solve this issue, this project is using pinia:^2.0.16 and Vue:3.2.37

This is the error:

Type '{}' is missing the following properties from type 'Order': id, 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(){
    .....
    },
   ...
   ...
}

Models/ShoppingCart.ts

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

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

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

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

Models/Category.ts

import type { Product } from '@/Models/Product'
export interface Category {
  id: number
  name: string
  slug: string
  products?: Product[]
}

Models/User.ts

import type { Order } from './Order'

export interface User {
  id: number
  name: string
  email: string
  orders: Order[]
}

I am getting the typescript error in the order property of the InitialState:

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

How can I solve this error please? thank you

CodePudding user response:

So, to have it as proper answer as mentioned in the comments above, the object should be null.

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

and therefore

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