An array in TypeScript is a collection of elements of the same type. TypeScript provides two ways to define an array type:
[]
syntax: type ArrayName = Type[]
. For example, number[]
represents an array of numbers.Array
type: type ArrayName = Array<Type>
. For example, Array<number>
also represents an array of numbers.// Defining an array of numbers using [] syntax
let numbers: number[] = [1, 2, 3, 4, 5];
// Defining an array of strings using generic Array type
let fruits: Array<string> = ['apple', 'banana', 'cherry'];
// Accessing elements
console.log(numbers[0]); // Output: 1
// Modifying elements
numbers[1] = 10;
console.log(numbers); // Output: [1, 10, 3, 4, 5]
// Adding elements
numbers.push(6);
console.log(numbers); // Output: [1, 10, 3, 4, 5, 6]
// Removing elements
numbers.pop();
console.log(numbers); // Output: [1, 10, 3, 4, 5]
for...of
loop to iterate over an array.let numbers: number[] = [1, 2, 3];
for (let num of numbers) {
console.log(num);
}
filter
method to create a new array with elements that pass a test.let numbers: number[] = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
let arr = [1, 2, 3];
, use let ages: number[] = [18, 20, 22];
A tuple in TypeScript is an array with a fixed number of elements where each element can have a different type. The order and types of elements in a tuple are predefined. For example, [string, number]
represents a tuple where the first element is a string and the second element is a number.
// Defining a tuple
let person: [string, number] = ['John', 30];
// Accessing elements
console.log(person[0]); // Output: John
console.log(person[1]); // Output: 30
// Modifying elements
person[1] = 31;
console.log(person); // Output: ['John', 31]
function printPersonInfo(person: [string, number]) {
console.log(`${person[0]} is ${person[1]} years old.`);
}
let person: [string, number] = ['Alice', 25];
printPersonInfo(person);
type PersonTuple = [string, number];
let person: PersonTuple = ['Bob', 40];
Arrays and tuples are essential data structures in TypeScript. Arrays are great for storing collections of elements of the same type, and they offer a wide range of built - in methods for manipulation. Tuples, on the other hand, are useful when you need to represent a fixed number of values of different types. By understanding the fundamental concepts, usage methods, common practices, and best practices of working with arrays and tuples in TypeScript, you can write more reliable and maintainable code.