Skip to content

元组

数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。

元组起源于函数编程语言(如 F#),这些语言中会频繁使用元组。

简单的例子

定义一对值分别为 stringnumber 的元组:

ts
let tom: [string, number] = ['Tom', 25];

当赋值或访问一个已知索引的元素时,会得到正确的类型:

注意

因为笔者使用的是 Typescript 5.3.3版本,在测试时 先声明后赋值语句 或者先声明 后只赋值一个项目的时候编译失败了,笔者猜测可能是由于Typescript高版本已经限制此种语法了,但是具体是否是该原因并未测试,在查询网上关于各个版本新特性时未看到有该内容的说明。

ts
let tom: [string, number];
tom[0] = 'Tom';
tom[1] = 25;

tom[0].slice(1);
tom[1].toFixed(2);

也可以只赋值其中一项:

ts
let tom: [string, number];
tom[0] = 'Tom';

但是当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。

ts
let tom: [string, number];
tom = ['Tom', 25];
let tom: [string, number];
tom = ['Tom'];

// Property '1' is missing in type '[string]' but required in type '[string, number]'.

越界的元素

当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型:

ts
let tom: [string, number];
tom = ['Tom', 25];
tom.push('male');
tom.push(true);

// Argument of type 'true' is not assignable to parameter of type 'string | number'.

Released under the MIT License.