1. 数组数据类型定义
在TypeScript中,数组类型有多种定义方式,如:类型+方括号、数组泛型、接口、类数组等。
2. 数组的应用
a. [类型+方括号]表示法
let fibonacci: number[] = [1, 1, 2, 3, 5];//数组中不允许出现其他的类型,如果定义了特定类型的数组let fibonacci2: number[] = [1, '1', 2, 3, 5];//编译出错- error TS2322: Type 'string' is not assignable to type 'number'.
数组方法参数也是受数组定义时所约束
let fibonacci: number[] = [1, 1, 2, 3, 5];//方法或者属性也是不能是其他类型,提示出错fibonacci.push('8') ;//编译错误- error TS2322: Type 'string' is not assignable to type 'number'.
b. 数组泛型
let fib: Array<number> = [1, 1, 2, 3, 5];fib.push(8) ;console.log('fib:',fib) ;
c. 用接口表示数组
interface NumberArray {[index: number]: number}let fibArray: NumberArray = [1, 1, 2, 3, 5]
NumberArray表示:只要是索引数据类型时数值事,name值必须是数值。虽然接口也可以来描述数组,但是一般不采用此类做法。
d. 类数组
类数组(Array-like Object) 不是数组类型,比如arguments
function sum() {let args: number[] = arguments;}//编译错误- error TS2740: Type 'IArguments' is missing the following properties from type 'number[]': pop, push, concat, join, and 15 more.
上述示例中,arguments实际上是个类数组,但是不能用普通的数组方式来描述,需要接口的方式,如下:
function sum() {let args: {[index: number]: number;length: number;callee: Function;} = arguments;}
在上述示例中,我们除了约束当索引的数据类型为数值时,值的类型必须是数值外,也约束了他的两个属性:length、callee
事实上常用的类数组都有自己的接口定义,如:IArguments、NodeList、HTMLCollection等。
function sumFunc() {let args: IArguments = arguments}
e. any在数组中的应用
let list: any[] = ['hello', 22, { website: 'www.baidu.com' }, 'male', true]
