Open In App

How arrays works in TypeScript ?

Last Updated : 21 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Array in TypeScript is just similar to an array in other programming languages. The array contains homogeneous values means a collection of multiple values with different data types. TypeScript array is also fixed size, can not be resized once created. An array is a type of data structure that stores the elements of a similar data type and considers it as an object too.

How array work?

Array allocates in sequential memory blocks. Each memory block represents an array element. Elements of an array are accessed using the index of array elements for example to access 1st element of the array we need to access it using the 0th index as an index of an array starts from 0th index. Similarly, other elements get accessed using their index locations. 

How to declare array in TypeScript?

The array can be written in two ways:

Using the type of elements followed by [ ] to denote an array of that element type:

var list : number[] = [1,2,3,4,5];

Using generic array type:

var list : Array<number>=[1,2,3,4,5];

How to access array elements?

To access an element of a given array we must have to write array_name with a subscript.

Example:

Javascript




var arr : number [ ] = [1, 2, 3, 4, 5];
  
// Printing data
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[4]);


Output: 

1
2
3
5

Reference: https://www.typescriptlang.org/docs/handbook/basic-types.html#array


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads