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

const numbers: number[] = [1, 2, 3, 4, 5]; // Array of numbers const names: string[] = ['John', 'Jane', 'Alice']; // Array of strings

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

const numbers = [1, 2, 3, 4, 5]; // Array of numbers const names = ['John', 'Jane', 'Alice']; // Array of strings

Using the Array constructor

const mixedArray = new Array(5); // Array of 5 undefined elements const emptyArray = new Array<string>(); // Empty array of strings

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

const mixedArray = new Array(5); // Array of 5 undefined elements const emptyArray = new Array(); // Empty array of strings

Accessing Elements

You can access individual elements of an array using their index within square brackets:

console.log(numbers[0]); // Output: 1 console.log(names[2]); // Output: Alice

Iterating through Arrays

There are various ways to iterate through an array and access each element:

For loop

for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); }

For-of loop

for (const number of numbers) { console.log(number); }

forEach method

numbers.forEach(number => console.log(number));

Array Type Annotations and Literal Types

TypeScript allows you to annotate arrays with specific types or literal types:

let employeeIds: number[] = [101, 102, 103]; let weekdays: 'Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday'[] = ['Monday', 'Tuesday'];

Literal types restrict the array to specific values, providing more type safety.

Array Destructuring

Destructuring allows extracting values from arrays easily:

let [first, second, ...rest] = numbers; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5]

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.

let numbers: number[] = [1, 2, 3]; numbers.push(4, 5); // Result: [1, 2, 3, 4, 5]

pop(): T | undefined

Removes the last element from an array and returns it.

let lastElement = numbers.pop(); // Result: lastElement = 5, numbers = [1, 2, 3, 4]

forEach(callback: (element: T, index: number, array: T[]) => void)

Executes a provided function once for each array element.

numbers.forEach(num => console.log(num)); // Output: 1, 2, 3, 4

map(callback: (element: T, index: number, array: T[]) => U)

Creates a new array by applying a function to each element in the array.

let squaredNumbers = numbers.map(num => num * num); // Result: [1, 4, 9, 16]

filter(callback: (element: T, index: number, array: T[]) => boolean)

Creates a new array with elements that pass the test implemented by the provided function.

let evenNumbers = numbers.filter(num => num % 2 === 0); // Result: [2, 4]

indexOf(searchElement: T, fromIndex?: number)

Returns the first index at which a given element can be found in the array.

let index = numbers.indexOf(3); // Result: 2

slice(start?: number, end?: number)

Returns a shallow copy of a portion of an array into a new array object.

let subset = numbers.slice(1, 3); // Result: [2, 3]

concat(...items: (T[] | T)[])

Combines two or more arrays.

let additionalNumbers = [6, 7]; let combinedArray = numbers.concat(additionalNumbers); // Result: [1, 2, 3, 4, 6, 7]

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.

let sum = numbers.reduce((acc, num) => acc + num, 0); // Result: 10

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.