SIGN IN SIGN UP
2016-06-02 11:38:23 +08:00
# 元组Tuple
> 在 TypeScript 中,元组类型表示一些特定类型组合成的数组类型。
## 简单的例子
定义一对值分别为 `string``number` 的元组:
2016-06-02 22:05:55 +08:00
```ts
let xcatliu: [string, number] = ['Xcat Liu', 25];
```
当赋值或访问一个已知索引的元素时,会得到正确的类型:
2016-06-02 21:21:32 +08:00
```ts
let xcatliu: [string, number];
2016-06-02 22:05:55 +08:00
xcatliu[0] = 'Xcat Liu';
xcatliu[1] = 25;
xcatliu[0].slice(1);
xcatliu[1].toFixed(2);
```
2016-06-02 22:10:55 +08:00
即使只赋值其中一项也可以:
2016-06-02 21:21:32 +08:00
2016-06-02 22:05:55 +08:00
```ts
let xcatliu: [string, number];
xcatliu[0] = 'Xcat Liu';
```
但是当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。
2016-06-02 22:09:30 +08:00
```ts
let xcatliu: [string, number];
xcatliu = ['Xcat Liu', 25];
```
2016-06-02 22:05:55 +08:00
```ts
let xcatliu: [string, number] = ['Xcat Liu'];
// index.ts(1,5): error TS2322: Type '[string]' is not assignable to type '[string, number]'.
// Property '1' is missing in type '[string]'.
```
```ts
let xcatliu: [string, number];
xcatliu = ['Xcat Liu'];
2016-06-02 22:09:30 +08:00
xcatliu[1] = 25;
2016-06-02 22:05:55 +08:00
// index.ts(2,1): error TS2322: Type '[string]' is not assignable to type '[string, number]'.
// Property '1' is missing in type '[string]'.
2016-06-02 21:21:32 +08:00
```
## 越界的元素
2016-06-02 22:09:30 +08:00
当赋值给越界的元素时,它类型会被限制为元组中每个类型的联合类型:
2016-06-02 21:21:32 +08:00
```ts
let xcatliu: [string, number];
xcatliu = ['Xcat Liu', 25, 'http://xcatliu.com/'];
```
```ts
let xcatliu: [string, number];
2016-06-02 22:05:55 +08:00
xcatliu = ['Xcat Liu', 25];
xcatliu.push('http://xcatliu.com/');
2016-06-02 21:21:32 +08:00
xcatliu.push(true);
2016-06-02 22:05:55 +08:00
// index.ts(4,14): error TS2345: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
2016-06-02 21:21:32 +08:00
// Type 'boolean' is not assignable to type 'number'.
```
2016-06-02 22:09:30 +08:00
当访问一个越界的元素,也会识别为元组中每个类型的联合类型:
2016-06-02 21:21:32 +08:00
```ts
let xcatliu: [string, number];
xcatliu = ['Xcat Liu', 25, 'http://xcatliu.com/'];
2016-06-02 21:32:41 +08:00
console.log(xcatliu[2].slice(1));
2016-06-02 21:21:32 +08:00
2016-06-02 21:27:52 +08:00
// index.ts(4,24): error TS2339: Property 'slice' does not exist on type 'string | number'.
2016-06-02 21:21:32 +08:00
```
2016-07-11 20:13:44 +08:00
之前提到过,[如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有的属性或方法。](../basics/union-types.md#访问联合类型的属性或方法)
2016-06-02 21:42:43 +08:00
2016-07-04 21:39:17 +08:00
> Tip: 元组的概念来源于 [C#][C# Tuple]。区别是C# 中的元组是只读的。
2016-06-02 21:21:32 +08:00
## Links
- [Handbook - Basic Types # Tuple](http://www.typescriptlang.org/docs/handbook/basic-types.html#tuple)
- [中文手册 - 基础类型 # 元组 Tuple](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Basic%20Types.html#元组-tuple)
2016-07-04 21:39:17 +08:00
- [C# Tuple]
2016-06-02 22:05:55 +08:00
2016-07-04 21:39:17 +08:00
[C# Tuple]: https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx