Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
¿Cómo establecer el tipo para el objeto de estado en pinia?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 ).

  1. 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 ).

  2. 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 } } })
over 4 years ago · Santiago Trujillo Report

0

o simplemente así

 interface IUserState { user: null | IUser } export const useUserStore = defineStore({ id: 'user', state: (): IUserState => ({ user: null, }) ...
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!