<>TypeScript Array and Yuanzu in

In this paper, we discuss TypeScript Array and Yuanzu in , Discuss the difference between the two and the application .

<>1. array

stay TypeScript An array can store a collection of elements , It can be of the same type or different types . You can define arrays in two ways :
type MyArray = string[];
A single data type is defined here . The following definition includes multiple types of arrays :
type MyArray = Array<string | number>;
Similarly, define the array in the following way , Infer by type , The effect is the same as above :
const numberArray = [1, 2, 3, 4, 5]; const mixedArray = ['a', 2, 'c'];
The problem with this definition is that you don't know exactly what type each element is , No further type checking is possible :
const item = mixedArray[2];
here item The data type is string | number, To determine the specific type, the typeof Carry out additional checks .
TypeScript Provides methods to define precise element types , Now let's talk about Yuanzu .

<>2. Yuanzu

The syntax for defining Yuanzu is as follows :
type FixedArray = [string, number, string];
Each element can be assigned a data type :
const mixedArray: FixedArray = ['a', 2, 'c']; const first = mixedArray[0]; //
string const second = mixedArray[1]; // number
But there are some strange phenomena that need to be explained . This is a fixed length array , Display settings for each element type , But can we access elements beyond a fixed length ? We can , What is the data type ?
const fourth = mixedArray[3]; // string | number
We got it string | number data type .
ok , If we set the correct data type for elements out of scope , And then assign the value , Can the type be determined ?
mixedArray[3] = 4; const fourth = mixedArray[3]; // string | number
No , We can assign values to elements outside the scope , But it is still a hybrid of known array element types .

Therefore, you can determine the element data type by using meta ancestor , But don't go beyond that , Yuanzu can be understood as a fixed length , Out of range cannot guarantee its type .
JavaScript There is no ancestor type , It can only be used in the end JavaScript Arrays represent ancestors , Although it can check the area you visit , However, there is no guarantee that other modules will not change the value of the array .

<>3. summary

Yuanzu is very useful , But it's kind of crazy , be based on JavaScript How can our language not be crazy .
Arrays are generally used to hold collections of elements of the same type , Yuanzu can store different types of element collections , Both can be used as function parameters . Need to know when applying JavaScript Array properties of .