前言

在TypeScript中,数组类型有多种定义方式,比较灵活

「类型+方括号」表示法

  1. let arr: number[] = [1,2,3,4];
  2. arr.push('5');//数组中是不允许出现其它类型的值
  3. Argument of type '"4"' is not assignable to parameter of type 'number'.

数组泛型

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

  1. let arr: Array<number> = [1,2,3,4];
  2. 注意:这里也不可以出现没有定义的类型值

具体看一参考:https://www.yuque.com/along-n3gko/ezt5z9/ipwwmr

用接口表示数组

用接口来描述数组,这里定义接口NumberArr,表示只要索引类型是number类型时,那么它的值就必须是number或者string

  1. interface NumberArr {
  2. [index: number]: number | string
  3. }
  4. let arr: NumberArr = [1,2,3,4, '5'];
  5. 如果数组想定义任意类型值
  6. interface NumberArr {
  7. [index: number]: any
  8. }
  9. let arr: NumberArr = [1,2,3,4, '5', false, {a: 1}];

类数组

类数组(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.

我们应该用接口去描述它。

  1. function Fn () {
  2. let arg: {
  3. [index: number]: number;
  4. length: number;
  5. callee: Function
  6. } = arguments;
  7. console.log(arg); //[Arguments] {}
  8. }
  9. //定义接口约束索引为number类型,还约束了length和callee

事实上常用的类数组都有自己的接口定义,如Iarguments,NodeList,HTMLCollection等.下面的等同与上面定义的接口。

  1. function Fn () {
  2. let arg: IArguments = arguments;
  3. console.log(arg); //[Arguments] {}
  4. }

任意类型数组

any表示在数组中允许出现任意类型值

  1. let arr: any[] = [1,'2',true, {a: 1}];