1 空数组
const emptyArr: [] = [];emptyArr.length; // 0// ERROR: 类型“number”的参数不能赋给类型“never”的参数。emptyArr.push(1);
2 基本数组
常用的使用 : 类型[] 的形式定义同一类型的数组,且定义后会对该数组的某些方法也进行一些限制。
let score: number[]; // 定义由数值组成的数组score.push(95); // OKscore.push('88'); // ERROR: 类型“string”的参数不能赋给类型“number”的参数。score = [82,89,100,'99']; // ERROR: 类型“string”的参数不能赋给类型“number”的参数。
3 泛型数组
也可以使用数组泛型(Array Generic) : Array<elemType> 来表示数组:具体查看泛型。
const array1: Array<number> = [1, 2, 3];array1.push(4);// ERROR: 类型“string”的参数不能赋给类型“number”的参数。array1.push('a');
还有一些特殊的数组约束,如:只读数组
const array2: ReadonlyArray<string> = ['a', 'b', 'c'];// ERROR: 类型“readonly string[]”上不存在属性“push”。array2.push('d');
注:同样的还有 ReadonlyMap, ReadonlySet
4 接口数组
通过接口 (Interfaces) 的方式也能约束数组的类型
interface INumberArray {[index: number]: number;}let arr: INumberArray;// ERROR: 不能将类型“string”分配给类型“number”。arr = [1,2,3,'4'];// ❗注意此时相当于自定义类数组接口,它没有数组的属性和方法// 除非该接口继承 Array 接口类型 extends Array<any>// ERROR: 类型“NumberArray”上不存在属性“push”。arr.push('5');// ERROR: 类型“INumberArray”上不存在属性“length”。arr.length;
但有些复杂一般不这么做,但也有例外,对于类数组 (Array-like Object) 如 arguments 用接口定义约束类型就更方便:
interface ICusArguments {[index: number]: any;length: number;callee: Function;}function fn(): void {let args: ICusArguments = arguments;}
❗注:
- 实际上常用的类数组, TypeScript 都已经为我们定义好了其接口,如
IArguments,NodeList,HTMLCollection等。 - 另一种常用的是
:any[]类型的数组,即允许数组中值类型出现任意值。
