【发布时间】:2020-01-14 17:08:12
【问题描述】:
每当我在元组上使用array.map 时,Typescript 都会将其推断为通用数组。例如,这里有一些简单的 3x3 数独游戏:
const _ = ' ' // a "Blank"
type Blank = typeof _
type Cell = number | Blank
type Three = [Cell, Cell, Cell]
type Board = [Three, Three, Three]
const initialBoard: Board = [
[_, 1, 3],
[3, _, 1],
[1, _, _],
]
// Adds a `2` to the first cell on the first row
function applyMove(board: Board): Board {
// ????errors here
const newBoard: Board = board.map((row: Three, index: number) => {
if (index === 0) return <Three> [2, 1, 3]
return <Three> row
})
return newBoard
}
function applyMoveToRow(row: Three): Three {
// return [2, 1, 3] // This works
const newRow: Three = [
2,
...row.slice(1, 3)
]
return newRow
}
TS 错误是:
Type '[Cell, Cell, Cell][]' is missing the following properties from type
'[[Cell, Cell, Cell], [Cell, Cell, Cell], [Cell, Cell, Cell]]': 0, 1, 2 .
here 在 TS Playground 中。
有没有办法告诉打字稿,当我映射一个元组时,它会返回一个相同类型的元组,而不仅仅是一个数组?我尝试过非常明确,注释我的所有返回值等,但它没有起到作用。
Typescript github 上有一个关于这个的讨论:https://github.com/Microsoft/TypeScript/issues/11312
但我无法从中找到解决方案。
【问题讨论】:
-
您是否也在询问您的
slice()问题? -
你使用的是什么版本的 TypeScript?看起来好像在 3.4 中已修复...
-
当然,解决这个问题的最简单方法是在
map之后添加` as Board`。并且在]之后为slice()问题加上` as Three`... -
@HereticMonkey 是的,
as Board确实可以解决问题,但感觉就像一个“补丁”。此外,playground 在 TS 3.5 中,仍然显示错误。 -
是的,我刚刚注意到...可能值得在他们的 GitHub 上提出问题。可能是回归。
标签: typescript tuples