TypeScript Arrays
Arrays are one of the most fundamental data structures in programming. They allow you to store multiple values in a single variable, making data management and manipulation more efficient. TypeScript enhances JavaScript arrays with strong typing capabilities, helping you catch potential errors during development rather than at runtime.
What is an Array in TypeScript?
In TypeScript, an array is a special type that can hold multiple values of the same data type or mixed types. Arrays are ordered collections, which means each element has a specific position (index) within the array.
Declaring Arrays in TypeScript
TypeScript provides multiple ways to declare arrays, giving you flexibility while maintaining type safety.
Basic Array Declaration
// Using square brackets notation
let numbers: number[] = [1, 2, 3, 4, 5];
// Using generic Array type
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
Arrays with Mixed Types
You can also create arrays that hold multiple types:
// Explicit union type
let mixed: (string | number)[] = ['hello', 1, 'world', 2];
// Using the any type (less type-safe)
let flexible: any[] = [1, 'hello', true, {}];
Empty Arrays
You can initialize empty arrays with type annotations to specify what they will contain:
// Empty number array
let scores: number[] = [];
// Empty string array
let names: Array<string> = [];
Accessing Array Elements
Array elements are accessed using their index, which starts from 0:
let colors: string[] = ['red', 'green', 'blue'];
console.log(colors[0]); // Output: "red"
console.log(colors[1]); // Output: "green"
console.log(colors[2]); // Output: "blue"
Array Properties and Methods
TypeScript arrays inherit all the properties and methods from JavaScript arrays.
Useful Array Properties
let numbers: number[] = [10, 20, 30, 40, 50];
// length property returns the number of elements
console.log(numbers.length); // Output: 5
Common Array Methods
Adding and Removing Elements
let fruits: string[] = ['Apple', 'Orange'];
// Add to the end
fruits.push('Banana');
console.log(fruits); // Output: ['Apple', 'Orange', 'Banana']
// Remove from the end
let lastFruit = fruits.pop();
console.log(lastFruit); // Output: Banana
console.log(fruits); // Output: ['Apple', 'Orange']
// Add to the beginning
fruits.unshift('Mango');
console.log(fruits); // Output: ['Mango', 'Apple', 'Orange']
// Remove from the beginning
let firstFruit = fruits.shift();
console.log(firstFruit); // Output: Mango
console.log(fruits); // Output: ['Apple', 'Orange']
Finding and Filtering Elements
let numbers: number[] = [10, 20, 30, 40, 50];
// Find the first element that satisfies a condition
let found = numbers.find(num => num > 25);
console.log(found); // Output: 30
// Filter creates a new array with elements that pass the test
let filtered = numbers.filter(num => num > 25);
console.log(filtered); // Output: [30, 40, 50]
// Check if at least one element passes a test
let hasEvenNumber = numbers.some(num => num % 2 === 0);
console.log(hasEvenNumber); // Output: true
// Check if all elements pass a test
let allAboveTen = numbers.every(num => num >= 10);
console.log(allAboveTen); // Output: true
Transforming Arrays
let numbers: number[] = [1, 2, 3, 4, 5];
// Map creates a new array with results of a function on each element
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
// Reduce executes a reducer function on each element, resulting in a single value
let sum = numbers.reduce((total, current) => total + current, 0);
console.log(sum); // Output: 15
// Join converts array to string with specified separator
let joined = numbers.join('-');
console.log(joined); // Output: "1-2-3-4-5"
Multidimensional Arrays
TypeScript supports multidimensional arrays (arrays of arrays):
// 2D array (matrix)
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Output: 6 (row 1, column 2)
// 3D array
let cube: number[][][] = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
];
console.log(cube[1][0][1]); // Output: 6
Tuple Types
TypeScript introduces tuples, which are arrays with fixed number of elements whose types are known:
// Tuple declaration
let person: [string, number, boolean] = ['John', 28, true];
console.log(person[0]); // Output: "John"
console.log(person[1]); // Output: 28
// Error: Type 'string' is not assignable to type 'number'
// person[1] = "twenty-eight";
Readonly Arrays
TypeScript allows you to make arrays readonly, preventing modification after creation:
// Readonly array
const names: readonly string[] = ["Alice", "Bob", "Charlie"];
// Error: Property 'push' does not exist on type 'readonly string[]'
// names.push("David");
// Alternative syntax
const ages: ReadonlyArray<number> = [25, 30, 35];
Real-World Examples
Managing a Shopping Cart
// Define a product interface
interface Product {
id: number;
name: string;
price: number;
}
// Create a shopping cart
let shoppingCart: Product[] = [];
// Add products to cart
function addToCart(product: Product): void {
shoppingCart.push(product);
console.log(`${product.name} added to cart`);
}
// Calculate total price
function calculateTotal(): number {
return shoppingCart.reduce((total, product) => total + product.price, 0);
}
// Usage
addToCart({ id: 1, name: "Laptop", price: 999.99 });
addToCart({ id: 2, name: "Mouse", price: 29.99 });
console.log(`Total: $${calculateTotal()}`);
// Output:
// Laptop added to cart
// Mouse added to cart
// Total: $1029.98
Managing Student Grades
interface Student {
name: string;
grades: number[];
}
// Calculate average grade for a student
function calculateAverage(student: Student): number {
const sum = student.grades.reduce((total, grade) => total + grade, 0);
return sum / student.grades.length;
}
// Find students with passing average (>= 70)
function getPassingStudents(students: Student[]): Student[] {
return students.filter(student => calculateAverage(student) >= 70);
}
// Example usage
const studentsData: Student[] = [
{ name: "Alice", grades: [85, 90, 92, 88] },
{ name: "Bob", grades: [75, 68, 72, 81] },
{ name: "Charlie", grades: [62, 65, 68, 69] }
];
const passingStudents = getPassingStudents(studentsData);
passingStudents.forEach(student => {
console.log(`${student.name}: ${calculateAverage(student).toFixed(2)}%`);
});
// Output:
// Alice: 88.75%
// Bob: 74.00%
Array Patterns and Best Practices
Destructuring Arrays
const colors: string[] = ['red', 'green', 'blue'];
// Basic destructuring
const [first, second, third] = colors;
console.log(first); // Output: "red"
console.log(second); // Output: "green"
// Skip elements
const [primary, , tertiary] = colors;
console.log(primary, tertiary); // Output: "red" "blue"
// Rest pattern
const [head, ...rest] = colors;
console.log(head); // Output: "red"
console.log(rest); // Output: ["green", "blue"]
Spread Operator
// Combine arrays
const numbers1: number[] = [1, 2, 3];
const numbers2: number[] = [4, 5, 6];
const combined = [...numbers1, ...numbers2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
// Clone an array
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // Output: [1, 2, 3]
console.log(copy); // Output: [1, 2, 3, 4]
Type Narrowing with Arrays
function processItems(items: (string | number)[]): void {
items.forEach(item => {
if (typeof item === 'string') {
// TypeScript knows item is a string here
console.log(item.toUpperCase());
} else {
// TypeScript knows item is a number here
console.log(item.toFixed(2));
}
});
}
processItems(['hello', 42, 'world', 3.14]);
// Output:
// HELLO
// 42.00
// WORLD
// 3.14
Performance Considerations
When working with large arrays in TypeScript (and JavaScript), consider these performance tips:
// Preallocate array size when possible
const largeArray = new Array(10000);
// Prefer for-of loops for iteration
function sumArray(numbers: number[]): number {
let sum = 0;
for (const num of numbers) {
sum += num;
}
return sum;
}
// Use typed arrays for numeric data processing
const floatArray = new Float64Array(1000);
for (let i = 0; i < floatArray.length; i++) {
floatArray[i] = Math.random();
}
Summary
TypeScript arrays extend JavaScript arrays with powerful type-checking capabilities. In this guide, we've covered:
- How to declare and initialize arrays with proper type annotations
- Accessing and modifying array elements
- Common array methods for manipulation and transformation
- Multidimensional arrays and tuples
- Readonly arrays for immutability
- Real-world examples showing practical applications
- Performance considerations and best practices
Arrays are fundamental data structures you'll use in almost every TypeScript application. Understanding how to properly work with arrays while leveraging TypeScript's type system will make your code more robust and maintainable.
Exercises
- Create a function that filters an array of mixed types, separating numbers and strings into two different arrays.
- Implement a simple to-do list application using arrays and TypeScript interfaces.
- Write a function that takes an array of numbers and returns a new array containing only unique values.
- Create a 2D array representing a tic-tac-toe board, with a function to check if a player has won.
- Implement a function that sorts an array of custom objects by a specified property.
Additional Resources
- TypeScript Official Documentation on Arrays
- MDN Web Docs: JavaScript Array
- TypeScript Deep Dive - Arrays
Happy coding with TypeScript arrays!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)