Estoy haciendo un juego de ajedrez y estoy usando Vue 3 y TypeScript con Pinia para la gestión del estado.
Quiero hacer algo como lo siguiente:
export const useStore = defineStore("game", { state: () => { return { moves: [], gameBoard: getInitialBoard(), playerTurn: PieceColor.White, previousPieceSelected: undefined } }, updatePreviousPieceSelected(piece: Piece | undefined ) { this.previousPieceSelected = piece } } })ActualizarGameState.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(); } };Sin embargo, me sale un error en la siguiente línea:
store.updatePreviousPieceSelected(currentPiece);Esa Pieza actual (de tipo Pieza) no se puede asignar al tipo indefinido. Encontré un truco para que esto funcione haciendo lo siguiente en mi tienda:
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; }Pero se siente kluge. ¿Hay otra forma de escribir la pieza anterior seleccionada en el retorno de estado inicial?
El tipo de this.previousPieceSelected se deduce del estado inicial y actualmente está inicializado en undefined , por lo que tiene un tipo de undefined (lo que significa que solo se le puede asignar un valor de undefined ).
Utilice la aserción de tipo en el valor undefined inicial (es decir, la palabra clave as más el tipo deseado de Piece | undefined ).
También tenga en cuenta que los parámetros opcionales se pueden especificar con ?: en lugar de | undefined Esta es solo una forma más simple de escribirlo.
export const useStore = defineStore("game", { state: () => { return { moves: [], previousPieceSelected: undefined as Piece | undefined, 1️⃣ } }, actions: { 2️⃣ updatePreviousPieceSelected(piece ?: Piece) { this.previousPieceSelected = piece } } })o simplemente así
interface IUserState { user: null | IUser } export const useUserStore = defineStore({ id: 'user', state: (): IUserState => ({ user: null, }) ...