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).
-
Use type assertion on the initial
undefinedvalue (i.e., theaskeyword plus the desired type ofPiece | undefined). -
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
}
}
})