2017-01-15 23:58:09 +08:00
|
|
|
|
# 元组
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
2017-02-03 18:10:58 +08:00
|
|
|
|
数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。
|
|
|
|
|
|
|
2019-09-02 11:31:25 +08:00
|
|
|
|
元组起源于函数编程语言(如 F#),这些语言中会频繁使用元组。
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
|
|
|
|
|
## 简单的例子
|
|
|
|
|
|
|
|
|
|
|
|
定义一对值分别为 `string` 和 `number` 的元组:
|
|
|
|
|
|
|
|
|
|
|
|
```ts
|
2019-09-02 11:31:25 +08:00
|
|
|
|
let tom: [string, number] = ['Tom', 25];
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
当赋值或访问一个已知索引的元素时,会得到正确的类型:
|
|
|
|
|
|
|
|
|
|
|
|
```ts
|
2019-09-02 11:31:25 +08:00
|
|
|
|
let tom: [string, number];
|
|
|
|
|
|
tom[0] = 'Tom';
|
|
|
|
|
|
tom[1] = 25;
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
2019-09-02 11:31:25 +08:00
|
|
|
|
tom[0].slice(1);
|
|
|
|
|
|
tom[1].toFixed(2);
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
2017-01-14 19:12:27 +08:00
|
|
|
|
也可以只赋值其中一项:
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
|
|
|
|
|
```ts
|
2019-09-02 11:31:25 +08:00
|
|
|
|
let tom: [string, number];
|
|
|
|
|
|
tom[0] = 'Tom';
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
但是当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。
|
|
|
|
|
|
|
|
|
|
|
|
```ts
|
2019-09-02 11:31:25 +08:00
|
|
|
|
let tom: [string, number];
|
|
|
|
|
|
tom = ['Tom', 25];
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
```ts
|
2019-09-02 11:31:25 +08:00
|
|
|
|
let tom: [string, number];
|
|
|
|
|
|
tom = ['Tom'];
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
2019-09-02 11:31:25 +08:00
|
|
|
|
// Property '1' is missing in type '[string]' but required in type '[string, number]'.
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## 越界的元素
|
|
|
|
|
|
|
2018-08-07 17:17:34 +08:00
|
|
|
|
当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型:
|
2017-01-14 19:12:27 +08:00
|
|
|
|
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```ts
|
2019-09-02 11:31:25 +08:00
|
|
|
|
let tom: [string, number];
|
|
|
|
|
|
tom = ['Tom', 25];
|
|
|
|
|
|
tom.push('male');
|
|
|
|
|
|
tom.push(true);
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
2019-09-02 11:31:25 +08:00
|
|
|
|
// Argument of type 'true' is not assignable to parameter of type 'string | number'.
|
2017-01-09 15:51:21 +08:00
|
|
|
|
```
|
|
|
|
|
|
|
2017-01-14 19:12:27 +08:00
|
|
|
|
## 参考
|
2017-01-09 15:51:21 +08:00
|
|
|
|
|
2017-01-17 16:22:48 +08:00
|
|
|
|
- [Basic Types # Tuple](http://www.typescriptlang.org/docs/handbook/basic-types.html#tuple)([中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Basic%20Types.html#元组-tuple))
|