1

我正在制作一个国际象棋游戏,我正在使用 Vue 3 和带有 Pinia 的 TypeScript 进行状态管理。

我想做如下的事情:

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)不能分配给 undefined 类型。通过在我的商店中执行以下操作,我发现了一个 hack 来让它工作:

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?

4

2 回答 2

5

的类型this.previousPieceSelected是从初始状态推断出来的,并且它当前被初始化为undefined,因此它的类型是undefined(意味着它只能被分配一个值undefined)。

  1. 对初始值使用类型断言undefined(即as关键字加上所需的类型Piece | undefined)。

  2. 另请注意,可以使用?:而不是指定可选参数| undefined。这只是一种更简单的编写方式。

export const useStore = defineStore("game", {
  state: () => {
    return {
      moves: [],
      previousPieceSelected: undefined as Piece | undefined, 1️⃣
    }
  },
  actions: {                          2️⃣
    updatePreviousPieceSelected(piece ?: Piece) {
      this.previousPieceSelected = piece
    }
  }
})
于 2021-11-04T03:20:24.190 回答
1

或者就像这样

interface IUserState {
  user: null | IUser
}
    
export const useUserStore = defineStore({
  id: 'user',
  state: (): IUserState => ({
    user: null,
  })
...

于 2022-02-17T21:18:01.497 回答