如何在打字稿中指定由数字和数组组成的数组的类型?

How to specify the type of an array consisting of number and an array in typescript?

我有以下数据结构,我想将其作为参数传递给函数。

let structure = [6, [197,47,28,191,198,129,117,82,171]]

假定第一个元素始终是一个数字,第二个元素始终是一个数字数组。当我想将它传递给我的函数时,我的 IDE 建议输入类型如下:

function myFunc(structure:(number | number[])[]) {
    ....
}

这会导致问题,因为它不够具体。我知道第一个元素始终是数字,但根据我的类型声明,它不一定是。

如何在打字稿中正确声明此处的类型?

我会将其指定为类型

type MyStructure = [number,number[]] // give it a better name than MyStructure!

并将其用于函数参数

function myFunc(structure:MyStructure) {
    ....
}

Playground link 显示它将输入限制为您想要的

function myFunc(structure: [number, number[]]) {
    ....
}

这称为元组类型。