TypeScript Arrays
Arrays are a special type of object used to store ordered collections of values. In TypeScript, you can define arrays containing elements of specific types, gaining the benefits of type safety.
Creating Arrays
There are two main ways to declare an array:
-
Type + square brackets
[]: This is the most commonly used way. -
Generic array type
Array<Type>: Using generic syntax.
Both ways are equivalent; which one to choose depends on personal or team coding style preferences.
Accessing Array Elements
You can access elements in an array through their index (starting from 0).
Due to type checking, you cannot assign a value of the wrong type to an array element:
Array Properties and Common Methods
TypeScript arrays have the same properties and methods as JavaScript arrays.
length Property
Returns the number of elements in the array.
Methods that Modify Arrays
-
push(...items): Adds one or more elements to the end of the array and returns the new length. -
pop(): Removes and returns the last element of the array. -
shift(): Removes and returns the first element of the array. -
unshift(...items): Adds one or more elements to the beginning of the array and returns the new length. -
splice(start, deleteCount, ...items): Adds/removes elements at any position.
Methods for Iterating Arrays
-
forEach(callback): Executes a provided function once for each array element. -
map(callback): Creates a new array with the results of calling a provided function on every element in the array. -
filter(callback): Creates a new array with all elements that pass the test implemented by the provided function.
Multi-dimensional Arrays
You can also create multi-dimensional arrays (arrays of arrays).