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

Array type

Next, how is an array defined in TS?

// Each item in the array must be of type string. Hover over myFriends to see that it is
let myFriends: string[] = ['Alex'.'Bob'];

// What if an item in the array is not a string? Error: Can't assign type 'number' to type 'string'
let myFriends: string[] = ['Alex'.'Bob'.7];
// At this point, we can change the string to an associative type
let myFriends: (string | number) [] = ['Alex'.'Bob'.7];
Copy the code

In addition to constraining each item of the array, we can also constrain the data when we call certain methods

let myFriends: string[] = ['Alex'.'Bob'];
// Because the argument passed is not a string, the same error will be reported
myFriends.push(7);
Copy the code

In addition to using simple types, we can also use object types

Each item in the array must be of type object or an error will be reported.

let myFriends: {
    name: string; } [] = [{name: 'Alex'}, {name: 'Bob'}];
Copy the code

So, how do we define array types?

We can use the type +[] to represent an array type.

Problem: is a variableanimalDeclare the appropriate type

const animal: ______ = [10.10];
Copy the code

A. number B. any C. number []

Answer: C

parsing

Animal is assigned an array, so animal should be declared as an array type.

  • A – This optionnumberIs the basic data type. So the mistake.
  • B – although declared asanyYes, but obviously the variableanimalA more specific array type is more appropriate. So the mistake.
  • C – This option is the correct type.

Data – Array generics

There is no such thing as Generis in JavaScript, but it almost always exists in strongly typed languages. Let’s take a look at wikipedia’s definition of generics.

Generics are defined in the following two main ways: in the code of some types containing type parameters, that is, the parameters of the generic type can only represent the class, not the individual object. (This is the more common definition nowadays.) 1. Classes that contain arguments in programming. Its arguments can represent classes or objects, and so on. 2. Regardless of which definition is used, the parameters of a generic type must be specified when the generic type is actually used. Some strongly typed programming languages support generics. The main purpose is to enhance type safety and reduce the number of class conversions, but some generics support only partially.

As a superset of JavaScript, TypeScript does a number of things to address JavaScript’s inherent weakness as a weak language, including adding Generics. Generics is the ability to specify the type of a function, interface, or class when defining it, and then specify the type when using it.

Here we’ll use a generic array scenario to make a brief introduction.

CreateArray first, we implement a function createArray that creates an array of specified length and fills each entry with a default value: createArray

function createArray(length: number, value: any) :Array<any> {
    let result = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}

createArray(3.'x'); // ['x', 'x', 'x']
Copy the code

In the example above, we used the array generics mentioned earlier to define the type of the return value.

This code compiles without error, but an obvious flaw is that it does not define exactly the type of return value:

Array allows each entry of an Array to be of any type. But we expect that each item in the array should be the type of the input value.

Where generics come in handy:

function createArray<T> (length: number, value: T) :Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}

createArray<string> (3.'x'); // ['x', 'x', 'x']
Copy the code

In the example above, we add

after the function name, where T is used to refer to any input type, which can be used in the input value: T and output Array.

You can then specify that it is of type string when called. Of course, it is possible to let type inference be calculated automatically instead of specifying it manually:

function createArray<T> (length: number, value: T) :Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}

createArray(3.'x'); // ['x', 'x', 'x']
Copy the code

Type inference – Arrays

Next, let’s look at the application of type inference to arrays.

// The type is inferred from the following values
let myFriends = ['Alex'.'Bob'];
// There will also be an error
myFriends.push(7);
Copy the code

If we add a number type to an array, it is inferred to be a union type

let myFriends = ['Alex'.'Bob'.7];
// If we take an item of the array and call its methods, the second item is identified as the union type
// If we want to call methods that are numeric only, we get an error; Attribute 'toFixed' not found on type 'string'
myFriends[2].toFixed();
Copy the code

Again, an array deduces its type from each item in the array. If there are more than one item of different types in the array, then each item of the array is inferred to the union type of the previous type.

Problem: in strictly typed mode, variablesanimalIs of the type?

const animal = [{ name: 'panda'.weight: 10 }];
Copy the code

A. string | number

B. any

C. { name: string; weight: number }

D. { name: string; weight: number } []

Answer: D

parsing

The variable animal is assigned to an array, so the variable animal is inferred to a specific array type.

  • A – The union types of this option are all basic data types. So the mistake.
  • B – anyNot a specific array type. So the mistake.
  • C – This option is the object type. So the mistake.
  • D – This option is an array type and the structure type of the array element matches that of the assignment object. Therefore, correct.

Data: Class array

The array-like Object class is not an Array type, as in arguments:

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

// index.ts(2,7): error TS2322: Type 'IArguments' is not assignable to type 'number[]'.
// Property 'push' is missing in type 'IArguments'.
Copy the code

In fact, common class arrays have their own interface definitions, such as IArguments, NodeList, HTMLCollection, etc. :

function sum() {
    let args: IArguments = arguments;
}
Copy the code

Data: Represents the type of array using an interface

Interfaces can also be used to describe arrays:

interface NumberArray {
    [index: number] :number;
}
let fibonacci: NumberArray = [1.1.2.3.5];
Copy the code

NumberArray indicates that the value type must be number, as long as the type of index is number.