ts from scratch - day04

Learn about ts arrays today. There are many ways to define arrays in js. Similarly, there are many ways to define ts.

1. [Type + square brackets] notation

This is the easiest way, for example:
 

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

The first is to declare an array, and then the element type in the array. Since we have defined the element type of this array as number, this array can only be composed of elements of type number. It is not allowed to add other data types. It is worth noting What's more, the parameters in some methods in the array will also have some constraints. For example, I want to push an "8", which is also not possible.

2. Array generics

We can also define arrays with array generics

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

3. Interface

We can also define arrays with interfaces

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

NumberArray Representation: As long as the type of the index is a number, the type of the value must be a number.

Although interfaces can also be used to describe arrays, we generally don't do this because this method is much more complicated than the first two methods.

However, there is one exception, that is, it is often used to represent array-like.

array-like

Array-like (Array-like Object) is not an array type, such as  arguments:

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

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

In the above example, arguments it is actually a class array, which cannot be described by an ordinary array, but should be described by an interface:

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

In this example, in addition to constraining that when the type of the index is a number, the type of the value must be a number, we also constrain it to have  length and  callee two attributes.

In fact, commonly used class arrays have their own interface definitions, such as  IArgumentsNodeListHTMLCollection and so on:

Among them  IArguments is the type defined in TypeScript, which is actually:

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

Guess you like

Origin blog.csdn.net/qq_45662523/article/details/126449714