ts从零开始-day04

今天学习ts的数组,js中数组有多种定义方式,同样的,ts也是有多种定义方式

1、【类型+方括号】表示法

这是最简单的方法,例如:
 

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

首先是声明一个数组,接着是数组里面的元素类型,既然我们定义了这个数组的元素类型是number,所以这个数组只能有number类型的元素组成,添加其他的数据类型是不可以的,值得注意的是,数组中的一些方法中的参数也会做一些约束,比如我想push一个"8",这也是不可以的

2、数组泛型

我们也可以用数组泛型定义数组

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

3、接口

我们也可以用接口定义数组

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

NumberArray 表示:只要索引的类型是数字时,那么值的类型必须是数字。

虽然接口也可以用来描述数组,但是我们一般不会这么做,因为这种方式比前两种方式复杂多了。

不过有一种情况例外,那就是它常用来表示类数组。

类数组

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

function sum() {
    let args: number[] = arguments;
}

// Type 'IArguments' is missing the following properties from type 'number[]': pop, push, concat, join, and 24 more.

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

function sum() {
    let args: {
        [index: number]: number;
        length: number;
        callee: Function;
    } = arguments;
}

在这个例子中,我们除了约束当索引的类型是数字时,值的类型必须是数字之外,也约束了它还有 length 和 callee 两个属性。

事实上常用的类数组都有自己的接口定义,如 IArgumentsNodeListHTMLCollection 等:

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

interface IArguments {
    [index: number]: any;
    length: number;
    callee: Function;
}
let list: any[] = ['xcatliu', 25, { website: 'http://xcatliu.com' }];
//可以使用any表示数组可以出现任意类型

猜你喜欢

转载自blog.csdn.net/qq_45662523/article/details/126449714