在打字稿中使用 map 函数时确保类型安全

时间:2021-06-08 18:03:56

标签: typescript

我有以下类型

export type Player = 'x' | 'o'
export type GameFieldValue = null | Player;
export type Board = [
    [GameFieldValue, GameFieldValue, GameFieldValue],
    [GameFieldValue, GameFieldValue, GameFieldValue],
    [GameFieldValue, GameFieldValue, GameFieldValue],
]

假设我有一个 Board 类型的对象

const board : Board = [
    ['x','x','o'],
    ['o','x','x'],
    ['x','x','x']
]

现在,我需要一个可以反转棋盘所有值的函数(例如,'x' 变为 'o',反之亦然)

const boardInverted : Board = [
    ['o','o','x'],
    ['x','o','o'],
    ['o','o','o']
]

我想出的函数

function invertBoardValues(b:Board):Board {
    return b.map(row => row.map(val => val === 'x' ? 'o' : 'x'))
}

但是,我收到错误

Type '("x" | "o")[][]' is not assignable to type 'Board'.
Target requires 3 element(s) but source may have fewer.

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以使用 as Board

function invertBoardValues(b:Board):Board {
    return b.map(row => row.map(val => val === 'x' ? 'o' : 'x')) as Board;
}