我正在制作一個國際象棋游戲,我正在使用 Vue 3 和 TypeScript 和 Pinia 進行狀態管理。
我想做如下事情:
export const useStore = defineStore("game", {
state: () => {
return {
moves: [],
gameBoard: getInitialBoard(),
playerTurn: PieceColor.White,
previousPieceSelected: undefined
}
},
updatePreviousPieceSelected(piece: Piece | undefined ) {
this.previousPieceSelected = piece
}
}
})
更新GameState.vue
setup() {
const store = useStore()
const previousPieceSelected: Piece | undefined = store.previousPieceSelected;
let playerTurn: PieceColor = store.playerTurn;
const initialGameState: GameState = {
boardState: store.gameBoard,
playerTurn,
};
const updateGameState = (
cellRow: number,
cellCol: number,
currentPiece: Piece
) => {
if (
previousPieceSelected === undefined ||
previousPieceSelected.pieceType === PieceType.None
) {
store.updatePreviousPieceSelected(currentPiece);
}
if (
(previousPieceSelected !== currentPiece && (currentPiece.pieceType === PieceType.None || currentPiece.color !== previousPieceSelected.color))
) {
MovePiece(store.gameBoard, previousPieceSelected, {row: cellRow, col: cellCol} as Position)
store.updatePreviousPieceSelected(undefined);
store.changePlayer();
}
};
但是,我在以下行中收到錯誤訊息:
store.updatePreviousPieceSelected(currentPiece);
該 currentPiece(型別 Piece)不可分配給未定義型別。通過在我的商店中執行以下操作,我找到了一種方法來使其作業:
export const useStore = defineStore("game", {
state: () => {
return {
moves: [],
gameBoard: getInitialBoard(),
playerTurn: PieceColor.White,
previousPieceSelected: getInitialPreviousPieceSelected()
}
},
actions: {
changePlayer() {
this.playerTurn =
this.playerTurn === PieceColor.White
? PieceColor.Black
: PieceColor.White;
},
updatePreviousPieceSelected(piece: Piece | undefined ) {
this.previousPieceSelected = piece
}
}
})
function getInitialPreviousPieceSelected(): Piece | undefined {
return undefined;
}
但感覺很笨拙。有沒有另一種方法可以在初始狀態回傳中輸入 previousPieceSelected ?
uj5u.com熱心網友回復:
的型別this.previousPieceSelected是從初始狀態推斷出來的,它當前被初始化為undefined,因此它有一個型別undefined(意味著它只能被分配一個值undefined)。
對初始值使用型別斷言
undefined(即,as關鍵字加上所需的 型別Piece | undefined)。另請注意,可以使用
?:代替來指定可選引數| undefined。這只是一種更簡單的撰寫方式。
export const useStore = defineStore("game", {
state: () => {
return {
moves: [],
previousPieceSelected: undefined as Piece | undefined, 1??
}
},
actions: { 2??
updatePreviousPieceSelected(piece ?: Piece) {
this.previousPieceSelected = piece
}
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/348562.html
