TypeScript_3 数组类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 数组类型
let list1: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9]

// 指定了数组为number类型,就不允许数组中有其它类型
let list2: number[] = [1, 2, 3, 4, 5, "one"] //Type 'string' is not assignable to type 'number'.
//实则不影响
console.log(list2); //[ 1, 2, 3, 4, 5, 'one' ]
//方法也不允许
list2.unshift("zero") //Argument of type 'string' is not assignable to parameter of type 'number'.
console.log(list2); //['zero', 1,2, 3,4, 5,'one']

//定义任意类型的数组
let list3: any[] = [1, 2, 3, 4, 5, "one", "two", "three"]
console.log(list3); //[ 1, 2, 3, 4, 5, 'one', 'two', 'three' ]

// 数组泛型
let list4: Array<number> = [1, 2, 3, 4, 5]
console.log(list4); //[ 1, 2, 3, 4, 5 ]


//以接口表示数组
interface NumberArray {
[index: number]: number;
}

let list5: NumberArray = [1, 2, 3]
console.log(list5); //[ 1, 2, 3 ]


// 多维数组
let list6: number[][] = [[1, 2, 3], [1, 2, 3]]
console.log(list6);

function Arr(...args: any): void {
console.log(arguments);
let arr: IArguments = arguments
}

//这里的IArguments是TypeScript中定义了的类型实际是
interface IArguments1 {
[index: number]: any;
length: number;
callee: Function
}
Arr(100, 200, 300) //[Arguments] { '0': 100, '1': 200, '2': 300 }