In TypeScript, arrays are a collection of homogeneous elements stored in contiguous memory locations. Elements in arrays can be accessed by index, and indices begin from 0
.
The following diagram represents an array where the number 1 is stored at index 0
. The number 2 is stored at index 1
, and so on.
In TypeScript, arrays can be initialized in two ways:
let arrayName:dataType[] = [element1, elment2,...]
In the following code, we are creating the array weeks:string[]
, where weeks
is the array’s name, and string
is the element’s data type in the array.
The right side of the =
operator depicts the assignment of the values in an array separated by a comma ,
: ["monday","tuesday"]
to the array.
let weeks:string[] = ["monday","tuesday"]console.log(weeks)
let arrayName:Array<datatype> = [element1, element2, ...]
In the following code, weeksAndNumbers:Array<string>
is used to create an array. weeksAndNumbers
is the array’s name and the array type in a generic way. The Array<string>
is specified by the data type of the first element in the array.
let weeksAndNumbers:Array<string> = ["monday","tuesday"]console.log(weeksAndNumbers)
Running the code snippet below will throw the error Type 'number' is not assignable to type 'string'
because we are adding a number to a string array.
To overcome the issue, we can specify the data as any
.
//passing number to string arraylet weeks:string[] = ["monday",5]console.log(weeks)
//passing number to string arraylet weeks:any[] = ["monday",5]console.log(weeks)
We have seen how to create arrays, but we have some restrictions on passing elements of different data types to an array.
Even though the any
type is available, it is not ideal to use for every scenario. Therefore, we will discuss passing multiple data types by separating them with |
.
In the following code, we pass elements of string
and number
to an array by the |
separator. We can add as many elements as we want.
//we are informing to typescript that the array,//may contain a string or number or both.let weeks:(string | number)[] = ["monday",5]console.log(weeks)
To access any array element, use the index for that element enclosed in square brackets, []
.
let primes:number[] = [2,3,5,7]//accessing first element at index 0console.log(primes[0])//accessing last element at index 3console.log(primes[3])
We can create multi-dimensional arrays just by specifying another square bracket []
for each dimension.
In the following code, we create a 2D
array.
//2D Arraylet num:number[][] = [[1,2,3],[4,5,6],[7,8,9]]console.log(num)//accessing first elementconsole.log(num[0][0])