每当我使用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 http://www.typescriptlang.org/play/#code/MYewdgzgLgBA+jAvDA5KmB6DMCGMBEAQgDY5gDW+AsAFC1QCeADgKYwlnlIyOsgBm8WvWZsAwi2LFuYAK4BbAEYsATjAA+7UhWE1ebACoALFSzbIA2hKkAaGNeJ2HAXV372IHCoAm3C8dMWOwCzYJMzVzoaUEhYAEswOKg4nGJCTx8ALg8vX0taGEKYCzg7AEY7AGZnGwKii0q7UpgymrrCiwr4JraaSNosGABBb28IXBgAAwAmSZ4QHiM2fjiVaBhgSWlwReXV9ZUQAHdaflkwYGSdnCYmYgYAWRAANxYACkUM72z03IBKH5fGAAb3aG3A6zALCOvyyOR83Bgn1yADp5Dc3m9DkdsiEgjAEt4WAAPbJyJSqP5IAB8ILBRQJgjehJJSEQyAADFTTFBZCowDAADx42kWablKqRBkMnl8gXC8IsWnYsEAXz+YNl-JgUJhX1oqt0ZwuVwFNzujxeLAMIAASscscdcYqATA8XSaAzBlqBWKJTBqphsMY4uMjiAVOQIGCYpDofacW7FX56UVxanCiis9iURBiHFNm8upUNZ6ilKij6dfHjgagA这是在 TS Playground 里。
有什么方法可以告诉打字稿,当我映射一个元组时,它将返回一个同类的元组,而不仅仅是一个数组?我尝试非常明确地注释我的所有返回值等,但这并没有达到目的。
Typescript github 上有一个关于此的讨论:https://github.com/Microsoft/TypeScript/issues/11312 https://github.com/Microsoft/TypeScript/issues/11312
但我一直无法从中找到解决方案。