简介
元组是一种在 TypeScript 中表示一个已知元素数量和类型的数组。每个元素的类型都是已知的,这些类型不必相同。例如,你可以表示一个 string 和 number 对组成的元组如下:
let tuple: [string, number];
tuple = ['hello', 42]; // OK
// tuple = [42, 'hello']; // Error! Type 'number' is not assignable to type 'string'.
只读元组
与数组类似,你可以使用 readonly 关键字声明只读的元组。这意味着元组的内容和结构都不能被修改。
let readonlyTuple: readonly [string, number] = ['hello', 42];
// readonlyTuple[0] = 'world'; // Error! Index signature in type 'readonly [string, number]' only permits reading.
成员数量的推断
TypeScript 能够在没有显式类型注解的情况下推断元组的类型和成员数量:
let autoTuple = ['hello', 42]; // type of autoTuple is inferred as [string, number]
但这仍然是数组的一个特殊情况,因此如果你向 autoTuple 添加第三个元素,它的类型会转变为数组。
扩展运算符与成员数量
当你使用扩展运算符与元组结合时,你会得到一个数组,因为扩展运算符表示一系列不确定数量的元素。但这会保持元组内部类型的约束。
例如:
let a: [string, number] = ['hello', 42];
let b = [...a]; // b's type is (string | number)[]
然而,使用扩展运算符在元组的定义中可以用于创建新的元组,例如:
let firstTuple: [string, number] = ['hello', 42];
let secondTuple: [boolean, ...typeof firstTuple] = [true, ...firstTuple];
// secondTuple's type is [boolean, string, number]
此处,secondTuple 是一个新的元组,其第一个元素是布尔值,后面的元素与 firstTuple 的类型和顺序相匹配。