TypeScript Arrays
What are TypeScript Arrays?
TypeScript arrays are used to store multiple values of the same type in a single variable. Arrays in TypeScript provide a way to manage lists of data, making it easier to access, modify, and organize values. They are strongly typed, meaning you can define the type of elements the array will hold, such as number
, string
, or even custom types.
For example, an array of product names in a shopping cart allows easy access, addition, and removal of items, to handle the inventory or order processing.
Syntax of TypeScript Arrays
In TypeScript, arrays can be declared in two ways: using square brackets []
or the Array<type>
syntax.
Example Syntax:
- Using square brackets:
let numbers: number[] = [1, 2, 3];
- Using generic syntax:
let numbers: Array<number> = [1, 2, 3];
Both methods serve the same purpose, allowing flexibility in how arrays are defined.
TypeScript Array Methods
Here are the commonly used array methods in TypeScript, each serving different purposes:
pop()
: Removes and returns the last element of the array.push()
: Adds new elements to the end of the array and returns the new length.sort()
: Arranges the array elements in ascending or descending order.concat()
: Combines two or more arrays and returns the resulting array.indexOf()
: Finds the index of the first occurrence of a value in the array (returns-1
if not found).copyWithin()
: Copies part of the array to another location within the same array.fill()
: Replaces array elements with a static value, starting and ending at specified indexes.shift()
: Removes and returns the first element of the array.splice()
: Adds, removes, or replaces elements within the array.unshift()
: Adds one or more elements to the beginning of the array and returns the new length.includes()
: Checks if the array contains a specific element and returnstrue
orfalse
.join()
: Combines all array elements into a single string, separated by a specified delimiter.lastIndexOf()
: Returns the index of the last occurrence of a value in the array.slice()
: Extracts a portion of the array and returns it as a new array.toString()
: Converts the array into a comma-separated string.toLocaleString()
: Returns a localized string representation of the array.
Accessing Array Elements
Elements in a TypeScript array are accessed using their index, which starts from 0
. For example, let fruits: string[] = ["Apple", "Banana", "Cherry"];
allows accessing the first element with fruits[0]
. This feature is used for retrieving specific values or iterating over an array to perform operations like filtering or searching. Accessing elements is common in real-world tasks like displaying user-selected items or fetching configuration values from a settings array.
Example:
tsx
1let fruits: string[] = ["Apple", "Banana", "Cherry"];
2console.log(fruits[0]); // Output: Apple
Insert Array Elements
Adding elements to an array in TypeScript can be done using methods like push()
to append items or by assigning values directly to a specific index. For instance, fruits.push("Mango");
appends an element to the end of the array, while fruits[1] = "Peach";
replaces the second element. This flexibility makes arrays ideal for dynamic scenarios, such as adding new user inputs or extending a list of active items in an application.
Example:
tsx
1let fruits: string[] = ["Apple", "Banana"];
2fruits.push("Cherry"); // Adds to the end
3fruits[1] = "Mango"; // Replaces Banana with Mango
Print Array Elements
Printing array elements can be achieved using loops like for
, forEach
, or even map
. These methods iterate through the array and perform actions on each element. For example, fruits.forEach((fruit) => console.log(fruit));
logs each fruit to the console. Printing arrays is useful for debugging or displaying data, such as listing all items in a cart or showing a user's favorite songs.
Example:
tsx
1let numbers: number[] = [1, 2, 3];
2numbers.forEach((num) => console.log(num));
Remove Array Elements
Elements can be removed from arrays using methods like pop()
to remove the last element, shift()
to remove the first, or splice()
to remove elements at a specific position. For example, fruits.pop();
removes the last fruit from the array. Removing elements is useful when cleaning up data, such as removing expired tasks from a to-do list or deleting invalid entries in a dataset.
Example:
tsx
1let fruits: string[] = ["Apple", "Banana", "Cherry"];
2fruits.pop(); // Removes Cherry
3fruits.splice(0, 1); // Removes Apple
Readonly
TypeScript’s readonly
modifier prevents arrays from being modified, making them immutable. For example, let constants: readonly string[] = ["PI", "E"];
ensures that no elements can be added, removed, or altered. Readonly arrays are ideal for storing fixed data, like configuration constants or system defaults, that must remain unchanged throughout the application.
Example:
tsx
1let readonlyFruits: readonly string[] = ["Apple", "Banana"];
2// readonlyFruits.push("Cherry"); // Error: Cannot modify a readonly array
Type Inference
TypeScript automatically infers the type of an array based on its initial values. For instance, let numbers = [1, 2, 3];
infers the type as number[]
. This feature simplifies code writing while retaining type safety. Type inference is particularly useful when the array's type is clear from the context, such as initializing a list of product prices or user scores without explicitly declaring the type.
tsx
1let numbers = [1, 2, 3]; // Inferred as number[]