Arrays are one of the most commonly used data structures in programming, and TypeScript provides robust support for arrays with added type safety. With array types, you can specify the type of elements within an array, ensuring consistent and reliable code. This tutorial will walk you through the essentials of working with arrays in TypeScript, from basic usage to advanced array types, providing real-world examples and tips along the way.
Arrays in TypeScript allow you to store multiple values of a specified type in a single variable. This type-checking feature ensures that each element in the array is of the correct type, making your code more predictable and preventing runtime errors. TypeScript arrays are flexible and support various types, including numbers, strings, objects, and even custom types. This guide covers how to declare, manipulate, and use arrays effectively in TypeScript.
In TypeScript, you can define the type of elements that an array can hold. This ensures that only elements of the specified type are added to the array, reducing the chances of errors and making code easier to read and maintain.
To declare an array type, you use either the type[] syntax or the Array<type>
syntax. Both methods achieve the same result, so you can choose the one that best suits your style.
let numbers: number[] = [1, 2, 3, 4];
let fruits: Array<string> = ["apple", "banana", "cherry"];
In this example:
numbers
is an array of number types.fruits
is an array of string types.You can declare an array type by appending []
after the type, indicating that this variable holds an array of that specific type.
let cities: string[] = ["New York", "Paris", "Tokyo"];
let ages: number[] = [21, 34, 45];
TypeScript ensures that each element in cities is a string and each element in ages is a number.
Array<type>
SyntaxAnother way to declare an array type in TypeScript is by using the Array<type>
syntax.
let temperatures: Array<number> = [98.6, 99.1, 100.2];
let colors: Array<string> = ["red", "green", "blue"];
Both the type[]
and Array<type>
syntaxes are valid and equivalent, so it’s a matter of preference which one you use.
TypeScript’s array type comes with built-in methods for adding, removing, and manipulating elements. Here are some commonly used methods with examples.
push()
and pop()
push()
: Adds one or more elements to the end of an array.pop()
: Removes the last element from an array.let fruits: string[] = ["apple", "banana"];
fruits.push("cherry");
console.log(fruits); // Output: ["apple", "banana", "cherry"]
fruits.pop();
console.log(fruits); // Output: ["apple", "banana"]
shift()
and unshift()
shift()
: Removes the first element from an array.unshift()
: Adds one or more elements to the beginning of an array.let numbers: number[] = [2, 4, 6];
numbers.unshift(0);
console.log(numbers); // Output: [0, 2, 4, 6]
numbers.shift();
console.log(numbers); // Output: [2, 4, 6]
map()
The map()
method creates a new array by applying a function to each element of the original array.
let prices: number[] = [10, 20, 30];
let discountedPrices = prices.map(price => price * 0.9);
console.log(discountedPrices); // Output: [9, 18, 27]
filter()
The filter()
method creates a new array with all elements that pass a specified condition.
let ages: number[] = [15, 18, 22, 30];
let adults = ages.filter(age => age >= 18);
console.log(adults); // Output: [18, 22, 30]
forEach()
The forEach()
method allows you to execute a function on each element in the array.
let names: string[] = ["Alice", "Bob", "Charlie"];
names.forEach(name => console.log(`Hello, ${name}!`));
These methods are widely used for processing arrays in TypeScript, helping you perform operations on array elements efficiently.
TypeScript supports multidimensional arrays, which are arrays that contain other arrays. This can be useful when working with data that has rows and columns, like a matrix.
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // Output: 2
In this example, matrix is a two-dimensional array where each element is itself an array of numbers. You can access elements by specifying the row and column indices.
A tuple is a fixed-length array with specific types for each position. Unlike a standard array, where every element has the same type, tuples allow you to define multiple types within a single array.
let person: [string, number] = ["Alice", 30];
console.log(`Name: ${person[0]}, Age: ${person[1]}`);
In this example, person is a tuple with two elements:
string
.number
.Tuples are useful when working with data where each element represents a different type or field, such as a pair of coordinates or a database record.
In an e-commerce application, you might need to manage a shopping cart where each item has a name and a price.
interface Product {
name: string;
price: number;
}
let cart: Product[] = [
{ name: "Laptop", price: 899.99 },
{ name: "Mouse", price: 19.99 },
{ name: "Keyboard", price: 49.99 }
];
function calculateTotal(cart: Product[]): number {
return cart.reduce((total, item) => total + item.price, 0);
}
console.log(`Total Price: $${calculateTotal(cart)}`); // Output: Total Price: $969.97
In this example:
cart
is an array of Product
objects, each with name and price
properties.calculateTotal
function calculates the total price of all items in the cart.In a sports application, you might use tuples to store player information with a name and position.
type Player = [string, string];
let team: Player[] = [
["Alice", "Forward"],
["Bob", "Defender"],
["Charlie", "Goalkeeper"]
];
team.forEach(([name, position]) => {
console.log(`${name} plays as ${position}`);
});
In this example:
team
is an array of tuples, where each tuple holds a player’s name
and position
.forEach
method iterates over the array, printing each player’s name
and position
.type[]
and Array<type>
), both ensuring type consistency within the array.push()
, pop()
, map()
, filter()
, and forEach()
allow efficient manipulation of arrays.Arrays in TypeScript are a powerful tool for organizing and working with lists of data. This guide covered the basics of array types, including how to declare arrays, use common methods, and work with advanced types like multidimensional arrays and tuples. By understanding these concepts, you can make your TypeScript code more reliable, readable, and maintainable, ensuring that your arrays contain only the data types you expect. Happy coding with TypeScript arrays!