How to define an array of different generic types in TypeScript ? - GeeksforGeeks

26 Jul, 2021
In typescript, an array is a data type that can store multiple values of different data types sequentially. Similar to JavaScript, Typescript supports array declaration and there are multiple ways to do it.
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
Array Declaration and Initialization starting from 0
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.
Javascript
var fruits: Array<string>;fruits = ['Kiwi', 'Plums', 'Peaches','Apples','Lime','Cherries']; var Digits: Array<number>;Digits = [23, 34, 100, 124,];
Method 2: Declaration and initializing on the same line: An alternative of declaring and initializing the array in the same line.
Example:
  
Javascript
/* First method of usual array withsquare brackets and second method ofgeneric arrays for examples fruitsand Digits */ var fruits: string[] = ['Kiwi', 'Plums',    'Peaches', 'Apples', 'Lime', 'Cherries']; var fruits: Array < String >= ['Kiwi', 'Plums',    'Peaches', 'Apples', 'Lime', 'Cherries']; var Digits: number[] = [23, 34, 100, 124];var Digits: Array < number >= [23, 34, 100, 124]
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.
Javascript
/* In the first example we're associatingstring with string and second examplevivek has 2 values 3 and 5, as we can havemultiple values */var Capital: (string | string)[] = ['USA',    'Washington D.C.', 'United Kingdom',    'London', 'India', 'New Delhi',    'Thailand', 'Bangkok'];// orvar Employees: Array < string | number >    = ['Atul', 1, 'Vivek', 3, 5, 'Sania', 8];
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[1], it returns White. However it’s tedious if the array length is too long, thereby we use the second method(looping).
Javascript
var Chocolates: string[] = ['White',    'Dark', 'SemiSweet', 'BitterSweet']; Chocolates[0]; // Returns WhiteChocolates[1]; // Returns DarkChocolates[2]; // Returns SemiSweetChocolates[3]; // Returns BitterSweetChcoloates[4]; // Returns undefined
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.
Javascript
// Using loop for the given arraylet Cities: string[] = ['Pune', 'Mumbai', 'Nagpur'];  for (var i = 0; i < Cities.length; i++) {     // Output: Pune Mumbai Nagpur    console.log(Cities[i]);} for (var i in Cities) {     // Output: Pune Mumbai Nagpur    console.log(Cities[i]);}
varshagumber28
surindertarika1234
JavaScript-Questions
Picked
TypeScript
HTML
JavaScript
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?