如何在TypeScrip中使用元组的array.map? [英] How to use array.map with tuples in typescript?

查看:8
本文介绍了如何在TypeScrip中使用元组的array.map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我在元组上使用array.map时,类型脚本都会将其推断为泛型数组。例如,以下是一个简单的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游乐场。

有没有办法告诉TypeScrip,当我在元组上进行映射时,它将返回相同类型的元组,而不仅仅是一个数组?我试着非常明确地对所有返回值进行注释,等等,但没有起到作用。

GitHub上有一篇关于这方面的讨论:https://github.com/Microsoft/TypeScript/issues/11312

但我一直无法从中获得解决方案。

推荐答案

如果您不介意调整分配方式initialBoard,您可以将Board定义更改为:

interface Board  {
    [0]: Three,
    [1]: Three,
    [2]: Three,
    map(mapFunction: (row: Three, index: number, array: Board) => Three): Board;
}

您必须更改将文本分配给Board的方式:

const initialBoard: Board = <Board><any>[
    [_, 1, 3],
    [3, _, 1],
    [1, _, _],
]

这篇关于如何在TypeScrip中使用元组的array.map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆