<>TypeScript Array and Yuanzu in
In this paper, we discuss TypeScript Array and Yuanzu in , Discuss the difference between the two and the application .
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;
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 .
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; //
string const second = mixedArray; // 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; // 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 = 4; const fourth = mixedArray; // 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 .