1. Array type

Type + square brackets notation

let numArr: number[] = [1, 5, 2, 7, 5]; Let numArr: number[] = [1, '5', 2, 7, 5]; let numArr: number[] = [1, '5', 2, 7, 5]; // Type 'string' is not assignable to Type 'number'. // Type 'string' is not assignable to Type 'number' number[] = [1, 1, 2, 3, 5]; numArr.push('8'); // Argument of type '"8"' is not assignable to parameter of type 'number'Copy the code

Array generics

We can also use Array Generic Array

to represent an Array:

let arr: Array<number> = [1, 2, 3];
Copy the code

3. Use interfaces to represent arrays

The interface can also be used to describe arrays:

interface NumberArray { [index: number]: number; } let arr: NumberArray = [1, 1, 2, 3, 5]; NumberArray: As long as the index is of type number, then the value must be of type numberCopy the code

4. The type of array

Define an array of classes, not in the form of an array, but in terms of an interface

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

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

Or is it

interface IArguments {
    [index: number]: any;
    length: number;
    callee: Function;
}
function sum() {
    let args: IArguments = arguments;
}
Copy the code