TypeScript Arrays
Working with typed arrays in TypeScript
📚 What are TypeScript Arrays?
Arrays in TypeScript store multiple values of the same type. You can define arrays using type[] or Array<type> syntax. TypeScript ensures all elements match the specified type for safety.
// Array of numbers
let scores: number[] = [95, 87, 92];
// Array of strings
let names: string[] = ["Alice", "Bob", "Charlie"];
Output:
scores: [95, 87, 92]
names: ["Alice", "Bob", "Charlie"]
Array Declaration Syntax
Type[] Syntax
Most common way
let numbers: number[] = [1, 2, 3];
let words: string[] = ["hi"];
Array<Type>
Generic syntax
let numbers: Array<number>;
let words: Array<string>;
Type Inference
Let TypeScript figure it out
let numbers = [1, 2, 3];
// Inferred as number[]
🔹 Creating Arrays
Different ways to create typed arrays:
// Method 1: Direct initialization
let fruits: string[] = ["apple", "banana", "orange"];
// Method 2: Empty array with type
let scores: number[] = [];
scores.push(95);
scores.push(87);
// Method 3: Using Array constructor
let items: string[] = new Array("item1", "item2");
// Method 4: Type inference
let ages = [25, 30, 35]; // Inferred as number[]
console.log(fruits); // ["apple", "banana", "orange"]
console.log(scores); // [95, 87]
Output:
["apple", "banana", "orange"]
[95, 87]
🔹 Array Operations
Common operations with typed arrays:
let numbers: number[] = [1, 2, 3];
// Adding elements
numbers.push(4); // [1, 2, 3, 4]
numbers.unshift(0); // [0, 1, 2, 3, 4]
// Removing elements
numbers.pop(); // [0, 1, 2, 3]
numbers.shift(); // [1, 2, 3]
// Accessing elements
let first = numbers[0]; // 1
let last = numbers[numbers.length - 1]; // 3
// Array length
console.log(numbers.length); // 3
console.log(numbers); // [1, 2, 3]
Output:
3
[1, 2, 3]
🔹 Array Methods
Useful array methods in TypeScript:
let numbers: number[] = [1, 2, 3, 4, 5];
// map: Transform each element
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: Keep elements that match condition
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// find: Get first matching element
let found = numbers.find(n => n > 3);
console.log(found); // 4
// reduce: Combine all elements
let sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum); // 15
// includes: Check if element exists
console.log(numbers.includes(3)); // true
Output:
[2, 4, 6, 8, 10]
[2, 4]
4
15
true
🔹 Multi-dimensional Arrays
Arrays can contain other arrays:
// 2D array (array of arrays)
let matrix: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing elements
console.log(matrix[0][0]); // 1
console.log(matrix[1][2]); // 6
// Array of string arrays
let groups: string[][] = [
["Alice", "Bob"],
["Charlie", "David"],
["Eve"]
];
console.log(groups[0]); // ["Alice", "Bob"]
console.log(groups[2][0]); // "Eve"
Output:
1
6
["Alice", "Bob"]
Eve
🔹 Readonly Arrays
Prevent modifications to arrays:
// Readonly array - cannot be modified
let readonlyNumbers: readonly number[] = [1, 2, 3];
// ❌ These will cause errors:
// readonlyNumbers.push(4); // Error
// readonlyNumbers[0] = 10; // Error
// ✅ Reading is OK
console.log(readonlyNumbers[0]); // 1
console.log(readonlyNumbers.length); // 3
// Alternative syntax
let readonlyNames: ReadonlyArray<string> = ["Alice", "Bob"];
console.log(readonlyNames[0]); // Alice
Output:
1
3
Alice
🔹 Type Safety with Arrays
TypeScript prevents type errors in arrays:
// ✅ Correct: All elements match type
let numbers: number[] = [1, 2, 3];
numbers.push(4); // OK
// ❌ Error: Wrong type
// numbers.push("5"); // Error: Argument of type 'string' is not assignable
// ✅ Mixed types need union
let mixed: (number | string)[] = [1, "two", 3, "four"];
mixed.push(5); // OK
mixed.push("six"); // OK
console.log(mixed); // [1, "two", 3, "four", 5, "six"]
Output:
[1, "two", 3, "four", 5, "six"]
🔹 Practical Example
Real-world array usage:
// Student management system
let studentNames: string[] = ["Alice", "Bob", "Charlie"];
let studentScores: number[] = [95, 87, 92];
// Add new student
function addStudent(name: string, score: number): void {
studentNames.push(name);
studentScores.push(score);
}
addStudent("David", 88);
// Calculate average
function getAverage(scores: number[]): number {
let sum = scores.reduce((total, score) => total + score, 0);
return sum / scores.length;
}
console.log(`Students: ${studentNames.join(", ")}`);
console.log(`Average Score: ${getAverage(studentScores)}`);
Output:
Students: Alice, Bob, Charlie, David
Average Score: 90.5