「类型 + 方括号」表示法

最简单的方法是使用「类型 + 方括号」来表示数组:

  1. let fibonacci: number[] = [1, 1, 2, 3, 5];

数组的项中不允许出现其他的类型:

  1. let fibonacci: number[] = [1, '1', 2, 3, 5];
  2. // Type 'string' is not assignable to type 'number'.

数组泛型

我们也可以使用数组泛型(Array Generic) Array<elemType> 来表示数组:

  1. let fibonacci: Array<number> = [1, 1, 2, 3, 5];

用接口表示数组

接口也可以用来描述数组:

  1. interface NumberArray {
  2. [index: number]: number;
  3. }
  4. let fibonacci: NumberArray = [1, 1, 2, 3, 5];

NumberArray 表示:只要索引的类型是数字时,那么值的类型必须是数字。
虽然接口也可以用来描述数组,但是我们一般不会这么做,因为这种方式比前两种方式复杂多了。
不过有一种情况例外,那就是它常用来表示类数组。

类数组

类数组(Array-like Object)不是数组类型,比如 arguments

  1. function sum() {
  2. let args: number[] = arguments;
  3. }
  4. // Type 'IArguments' is missing the following properties from type 'number[]': pop, push, concat, join, and 24 more.

上例中,arguments 实际上是一个类数组,不能用普通的数组的方式来描述,而应该用接口:

  1. function sum() {
  2. let args: {
  3. [index: number]: number;
  4. length: number;
  5. callee: Function;
  6. } = arguments;
  7. }

在这个例子中,我们除了约束当索引的类型是数字时,值的类型必须是数字之外,也约束了它还有 lengthcallee 两个属性。
事实上常用的类数组都有自己的接口定义,如 IArguments, NodeList, HTMLCollection 等:

  1. function sum() {
  2. let args: IArguments = arguments;
  3. }

其中 IArguments 是 TypeScript 中定义好了的类型,它实际上就是:

  1. interface IArguments {
  2. [index: number]: any;
  3. length: number;
  4. callee: Function;
  5. }

any 在数组中的应用

一个比较常见的做法是,用 any 表示数组中允许出现任意类型:

  1. let list: any[] = ['xcatliu', 25, { website: 'http://xcatliu.com' }];