How to set the type for the state object in pinia?

The type of this.previousPieceSelected is inferred from the initial state, and it’s currently initialized to undefined, so it thus has a type of undefined (meaning it can only be assigned a value of undefined).

  1. Use type assertion on the initial undefined value (i.e., the as keyword plus the desired type of Piece | undefined).

  2. Also note that optional parameters can be specified with ?: instead of | undefined. This is just a simpler way of writing it.

export const useStore = defineStore("game", {
  state: () => {
    return {
      moves: [],
      previousPieceSelected: undefined as Piece | undefined, 1️⃣
    }
  },
  actions: {                          2️⃣
    updatePreviousPieceSelected(piece ?: Piece) {
      this.previousPieceSelected = piece
    }
  }
})

Leave a Comment