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

Examples of TypeScript

This article describes how to annotate arrays and tuples.Copy the code

Type annotation for an array

/ / 1
const numberArr: number[] = [1.2.3];
Copy the code

Only numeric items can exist in the array numberArr.

/ / 2
const arr: (number | string)[] = [1.2.3.'a'];
Copy the code

The array ARR can have both numeric and string values.

/ / 3
const objectArr: {name: string}[] = [{name: 'bear'}];
Copy the code

Each item in the array objectArr must be an object.

If you think about example 3 above, if the object has many attributes the code is very long, and it looks very complicated. At this point we can use type aliases to solve the problem.

Type the alias

A type alias simply means giving a type a new name. Type aliases make code structure clearer. Note: Type aliases are defined using the type keyword.

/ / 4
type User = {
    name: string,
    age: number
}
const userList: User[] = [
    {name: 'bear'.age: 10}];Copy the code

In the example above, each item in the userList array must be an object, and each object must contain the name and age attributes, neither missing nor redundant. In addition, type aliases are often used for union types (described below).

Tuples

/ / case 5
const point: (string | number)[] = ['dunhuang'.94.670.40.155];
Copy the code

The point array defined in example 5 will have only three values, with the first value representing locations and the second and third values representing coordinates. It looks fine, but we can swap the order of the items or change the number of items.

Therefore, in some scenarios, array binding alone may not suffice. To meet this requirement, tuples appear.

/ / case 6
const point: [string, number, number] = ['dunhuang'.94.670.40.155];
Copy the code

In example 6 above, a tuple point is defined. A tuple can be thought of as an extension of an array that represents an array with a known number and type of elements. Specifically, we know the type of the element at each position in the array. When we assign a value to a tuple, we need to have the same type and number of elements in each position.

Finish this! If this article helps you at all, please give it a thumbs up.