This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Array

TypeScript manipulates array elements just like JavaScript. There are two ways to define an array.

First, the element type can be followed by [] to represent an array of elements of that type:

Let arrOfNumbers: number[] = [1,2,3]Copy the code

An error will be reported if there are other types of values in the array:

Let arrOfNumbers: number[] = [1,2,3,'name']Copy the code

Error message:

If we were to use the Push method in the array, it would work if we added a numeric type, and the page would report an error if we added a value of another type.

Correct examples:

Let arrOfNumbers: number[] = [1,2,3]Copy the code

Examples of errors:

Let arrOfNumbers: number[] = [1,2,3] arrOfNumbers.Copy the code

Error message:

The second way is to use Array generics, Array< element type > :

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

Class Array likeObject)

  1. You can use property names to simulate the properties of arrays
  2. It can grow dynamicallylengthattribute
  3. If you force the class array to call the push method, the length attribute is expanded based on the value position.
function test(){
    console.log(arguments)
    arguments.length
    arguments[0]
}
Copy the code

In TypeScript, types:

We get an error if we call a method like forEach that doesn’t exist

function test(){
    console.log(arguments)
    arguments.length
    arguments[0]
    arguments.forEach();
}
Copy the code

Error message:

We also get an error if we add an array to a class array

function test(){
    console.log(arguments)
    arguments.length
    arguments[0]
    let arr: any[] = arguments
}
Copy the code

Error message:

TypeScript already defines many types, such as:

  • HTMLAllCollection
  • IArguments
  • NodeList

, etc.

Tuples

The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type. For example, you can define a pair of tuples of type string and number.

let user: [string,Number] = ['xiaochen',20]
Copy the code

Here we can also get an error if our types or quantities do not match one by one:

let user: [string,Number] = [20,'xiaochen']
Copy the code

Error message:

let user: [string,Number] = ['xiaochen',20,true]
Copy the code

Error message:

If we want to add some property values we can use some of the array methods like push:

let user: [string,Number] = ['xiaochen',20]
user.push('123')
Copy the code

Note: In this example, we can only add string or number types. If we add other types, an error will be reported

let user: [string,Number] = ['xiaochen',20]
user.push(true)
Copy the code

Error message: