How to define an array of different generic types in TypeScript ?
Declaring and Initializing Arrays:
- We can either use var or let for declaring an array.
- The difference is var is used if we want the variable to be reflected/implemented throughout the program and let for a specific block.
- Following are the syntax
Method 1: Declaring and initializing on a separate line: Here we declare an array and initialize on separate lines, as the example given below. Often it is used for producing cleaner and readable code. We use the square type bracket if we already know the type of array and arrow brackets if we are using generic ( does not restrict to one data type).
var Arrayname[:datatype]; // Declaration
Arrayname = [val1,val2,val3,valn..] // Initialization
Here we declare digits array with a generic type, number, so the first digit, 23 indicates the type of array(number). If we do not declare the type of array, it’s classified as any.
Method 2: Declaration and initializing on the same line: An alternative of declaring and initializing the array in the same line.
Note that the difference between the first and second methods is purely for cleaner code.
Declaring MultiType Array: The types are separated by “|” for each type and each corresponds to the previous element. In the below example, the capitals of the country are paired up (Thailand for Bangkok, New Delhi for India) and in the second example, we don’t have a string for the number 5, which means it’s independent and occupies the space just like other elements.
Accessing Array Elements:
Method 1: Index Access(Direct Access): Direct access is possible when we know the index and size of the array. In the above example, we know “Dark” occupies 1 index hence we Chocolates, it returns White. However it’s tedious if the array length is too long, thereby we use the second method(looping).
Method 2: Using loop: The large size of an array might be use looping instead of direct access to reduce the lines of code and for cleaner code. In the below example, we use for loop for parsing through the cities array and print it accordingly.
Alternatively, if we do not know the size of the array we use “in” the array to print the same.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.