Location>code7788 >text

typeScript array types (v)

Popularity:118 ℃/2024-11-21 11:01:58

typeScript array type declarations are divided into default array types and array generic declarations, which are described below.

Basic Array Type Declaration

// Declaring Array Types All Numeric Types
let arr: number[] = [1, 2, 4, 5, 7]

// You'll get an error. You can't specify a string as the value of an array.
let arr1: number[] = [1, 2, 3, 4, '23323']

// To solve the above type, you can use a union type

let arr2: (number | string)[] = [1, 2, 3, 5, '2222']

// Or use ANY type of formulation
let arr3: any[] = [1, 2, 3, 5, '2222']

So what array generalization?

Rule Array<type> something like this

// How Array Generics are Defined
let arr4:Array<number> = [1,2,3,4,5,6]

How an array contains multiple types can be defined like this

// If it's a mix of multiple data
let arr5: Array<number|string> =[1, 2, 3, '4', 5, 6]

So is there another way to define an array? Yes, there is, and that is to use the interface to simulate

following code

interface numberArr{
    [index:number]:number
}

let a:numberArr = [1,2,3,4,5,6,7]

//denotes: whenever the type of the index is numeric, then the type of the value must be numeric.

So how do you represent multiple multiple data types by modeling arrays through an interface, we can try to do this

interface NumberOrStringArr{
    [index:number]:number|string
}

let b:NumberOrStringArr = [1, 2, 3, '4', 5, 6]

It's okay to write it like that.

 

So how do you represent multidimensional arrays?

In the case of a two-dimensional array, we can express it this way, with the number of two preceding parentheses representing the dimensions of the array

let data:number[][] = [[1,2], [3,4]];

 

Then how to represent some class arrays, such as arguments, I'll introduce the representation of such arrays below

function fnArr(...args: any): void {
    //Wrong arguments are arrays of classes that can't be defined this way.
    let arr: number[] = arguments
    ('arr :>> ',arr);
}

fnArr(111, 222, 333)

For example, if we declare the above function, we find that an error is reported as follows

It means that class arrays don't have the methods of real arrays, so there's no way to define them in the same way as frame arrays, but we can do it this way (using the ts built-in object IArguments definition)

function fnArr(...args: any): void {
    //ts built-in objects IArguments Definitions
    let arr: IArguments = arguments
}
fnArr(111, 222, 333)

The actual ts built-in implementation of this object looks like this

 

//where IArguments is a type defined in TypeScript, which it actually is:
interface IArguments {
[index: number]: any;
length: number;
callee: Function;
}

The characteristics of the arguments are simulated through the interface

So what if the array is of type task, just use the any:[] definition

 

let anyArr:any[] = [1,'222',{a:1}]

 

In the next section we learn about function extensions