Introduction
Many times we are using array while creating applications or implementing functionality. In this article will learn the array in detail, and its types as well.
What is Array in TypeScript?
- We can store the similar or different types of values into it, which means the data type can be the same or different.
- We can declare an array the type of the elements followed by [].
- Elements are stored sequentially, based on syntax & can be accessed using Index.
- Array in TypeScript is similar to JavaScript.
- We have to declare an array before using it.
Syntax
Using square brackets we can declare an array like
- var/let myArrayName [:datatype] = [val1,val2,valn..]; //declaration & initialization
Using generic type we can declare an array like
- var/let myArrayName <element-type> = [val1,val2,valn..]; //declaration & initialization
Here initialization is not mandatory. We can use class/model as well.
Example
- let penManufacturs: string[] = ['Cello', 'Aurora', 'Parker', 'A.T Cross','Shanghai Hero'];
- for(let i : number = 0; i < penManufacturs.length; i++)
- {
- console.log("Index of an array is "+ i + " & the value is : " + penManufacturs[i]);
- }
By using generic type we can define an array like:
- let penManufacturs: <string>[] = ['Cello', 'Aurora', 'Parker', 'A.T Cross','Shanghai Hero'];
- for(let i : number = 0; i < penManufacturs.length; i++)
- {
- console.log("Index of an array is "+ i + " & the value is : " + penManufacturs[i]);
- }
Output
Both the examples give us the same output:
Index of an array is 0 & the value is : Cello
Index of an array is 1 & the value is : Aurora
Index of an array is 2 & the value is : Parker
Index of an array is 3 & the value is : A.T Cross
Index of an array is 4 & the value is : Shanghai Hero
Multi Type Array
- Multi Type array contains elements of different data types like number, string, boolean etc using a generic array type.
- The advantage is we can use different data types in a single array.
Syntax
- var/let myArrayName: (datatype1 | datatype2)[] = [val1,val2,valn..];
Example
In the below example we will print the even records as we would like to print the manufacturer name & price because elements are stored in a continuous manner so will consider the next element for price.
- let penManufactursWithDetails: (string | number) [] = ['Cello', 100, 'Aurora', 200, 'Parker', 300, 'A.T Cross', 400, 'Shanghai Hero', 500];
- for(let i : number = 0; i < penManufactursWithDetails.length; i++)
- {
- if(i % 2 == 0)
- console.log("Company Name is : " + penManufactursWithDetails[i] + " & the price is : " + penManufactursWithDetails[i + 1]);
- }

Sourav Kumar DasPosted Dec 6, 2019, 6:26 AM
Nice useful article Sir.