TypeScript Arrays
In TypeScript, arrays are used to store and manipulate collections of values. They can hold elements of the same or different types, providing flexibility for various data structures and algorithms. Let's explore the details of working with arrays in TypeScript with examples:
Creating Arrays
There are two main ways to declare an array in TypeScript:
Using square brackets
Running the TypeScript compiler (tsc) will generate the following JavaScript code:
Using the Array constructor
Running the TypeScript compiler (tsc) will generate the following JavaScript code:
Accessing Elements
You can access individual elements of an array using their index within square brackets:
Iterating through Arrays
There are various ways to iterate through an array and access each element:
For loop
For-of loop
forEach method
Array Type Annotations and Literal Types
TypeScript allows you to annotate arrays with specific types or literal types:
Literal types restrict the array to specific values, providing more type safety.
Array Destructuring
Destructuring allows extracting values from arrays easily:
Destructuring simplifies working with individual elements of an array.
Array Operations
In TypeScript, arrays come with a set of built-in methods that facilitate common operations like adding or removing elements, iterating through elements, and transforming arrays. Let's explore some of these array methods in detail with examples:
push(element: T)
Adds one or more elements to the end of an array and returns the new length.
pop(): T | undefined
Removes the last element from an array and returns it.
forEach(callback: (element: T, index: number, array: T[]) => void)
Executes a provided function once for each array element.
map(callback: (element: T, index: number, array: T[]) => U)
Creates a new array by applying a function to each element in the array.
filter(callback: (element: T, index: number, array: T[]) => boolean)
Creates a new array with elements that pass the test implemented by the provided function.
indexOf(searchElement: T, fromIndex?: number)
Returns the first index at which a given element can be found in the array.
slice(start?: number, end?: number)
Returns a shallow copy of a portion of an array into a new array object.
concat(...items: (T[] | T)[])
Combines two or more arrays.
reduce(callback: (accumulator: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T)
Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Conclusion
Arrays are versatile data structures used to store collections of values, accommodating elements of the same or different types. They offer a rich set of built-in methods for manipulation, including adding and removing elements, iterating, mapping, filtering, and more, providing developers with powerful tools to work with data in a structured and efficient manner.