Welcome to the exciting world of TypeScript arrays and tuples! This chapter will equip you with everything you need to know about these fundamental data structures, from the basics to advanced concepts. We'll delve into their creation, manipulation, iteration, and explore their unique properties, ensuring you become a TypeScript array and tuple master.
let colors: string[] = ["red", "green", "blue"]; // Array of strings
let numbers: number[] = [1, 2.5, 3]; // Array of numbers
console.log(colors[0]); // Output: "red" (accessing first element)
console.log(numbers[2]); // Output: 3 (accessing third element)
There are two primary ways to create arrays in TypeScript:
[]
) separated by commas.Array
Constructor: This method provides more flexibility but is less frequently used.
// Array literal syntax
let fruits: string[] = ["apple", "banana", "orange"];
// Array constructor (less common)
let vegetables = new Array("potato", "carrot", "broccoli");
The length
property of an array represents the total number of elements it holds. It’s a zero-based index, meaning the first element has an index of “0”.
let animals: string[] = ["cat", "dog", "bird"];
console.log(animals.length); // Output: 3
You can access individual elements within an array using their index within square brackets ([]
). Remember, indexing starts from “0”.
console.log(animals[1]); // Output: "dog" (accessing second element)
animals[0] = "lion"; // Replacing the first element
console.log(animals); // Output: ["lion", "dog", "bird"]
TypeScript arrays provide a rich set of built-in methods for performing common operations:
push()
: Adds one or more elements to the end of the array.
animals.push("fish");
console.log(animals); // Output: ["lion", "dog", "bird", "fish"]
pop()
: Removes and returns the last element from the array.
let lastAnimal = animals.pop();
console.log(lastAnimal); // Output: "fish"
console.log(animals); // Output: ["lion", "dog", "bird"]
shift()
: Removes and returns the first element from the array.
let firstAnimal = animals.shift();
console.log(firstAnimal); // Output: "lion"
console.log(animals); // Output: ["dog", "bird"]
unshift()
: Adds one or more elements to the beginning of the array.
animals.unshift("elephant", "monkey");
console.log(animals); // Output: ["elephant", "monkey", "dog", "bird"]
slice()
: Extracts a section of the array and returns a new array.
let selectedAnimals = animals.slice(1, 3); // Extracts elements from index 1 (inclusive) to 3 (exclusive)
console.log(selectedAnimals); // Output: ["monkey", "dog"]
concat()
: Merges two or more arrays and returns a new array.
let allAnimals = animals.concat(["panda", "tiger"]);
console.log(allAnimals); // Output: ["elephant", "monkey", "dog", "bird", "panda", "tiger"]
indexOf()
: Returns the first index at which a given element can be found in the array, or -1 if not found.
let animalIndex = animals.indexOf("dog");
console.log(animalIndex); // Output: 1
lastIndexOf()
: Returns the last index at which a given element can be found in the array, or -1 if not found.
let lastDogIndex = animals.lastIndexOf("dog");
console.log(lastDogIndex); // Output: 1 (since there's only one "dog")
join()
: Converts all elements of an array into a string, separated by a specified separator (comma by default).
let animalString = animals.join(", ");
console.log(animalString); // Output: "elephant, monkey, dog, bird"
reverse()
: Reverses the order of elements in the array in place.
animals.reverse();
console.log(animals); // Output: ["bird", "dog", "monkey", "elephant"]
There are several ways to iterate through the elements of an array in TypeScript:
for
loop: This classic approach allows you to access elements by their index.
for (let i = 0; i < animals.length; i++) {
console.log(animals[i]);
}
// Output:
// bird
// dog
// monkey
// elephant
for...of
loop: This loop iterates over the values of the array without needing an index.
for (let animal of animals) {
console.log(animal);
}
// Output:
// bird
// dog
// monkey
// elephant
forEach()
method: This method executes a provided function once for each element in the array.
animals.forEach(animal => console.log(animal));
// Output:
// bird
// dog
// monkey
// elephant
TypeScript arrays can be multidimensional, meaning they can store arrays within them, creating a grid-like structure.
let grid: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(grid[1][0]); // Output: 4 (accessing element at row 1, column 0)
Tuples, often considered a special kind of array, offer a unique way to manage data in TypeScript. This section delves deeper into their characteristics, use cases, and advanced concepts, empowering you to leverage them effectively in your code.
let employee: [string, number] = ["Alice", 30]; // String in slot 1, number in slot 2
// This is valid:
employee[0] = "Bob"; // Assigning a string to the first slot (string)
// This will cause a TypeScript error:
// employee[1] = "New Employee"; // Trying to assign a string to the second slot (number)
Destructuring allows you to unpack the elements of a tuple into individual variables with matching types.
let employee: [string, number] = ["John", 35];
let name = employee[0];
let age = employee[1];
// Using destructuring for cleaner syntax:
let [name, age] = employee;
console.log(name); // Output: "John"
console.log(age); // Output: 35
Feature | Array | Tuple |
---|---|---|
Length | Can be dynamic (can grow or shrink) | Fixed (must be defined at creation) |
Type Checking | Less strict (elements can have different types) | Strict (each position has a specific type) |
Use Cases | General-purpose collection of items | Fixed-size data with well-defined structure |
While tuples primarily deal with fixed-length and typed elements, TypeScript offers some advanced features to extend their capabilities:
...
) to capture remaining elements in a tuple as an array.
let colors: [string, string, ...string[]] = ["red", "green", "blue", "purple", "yellow"];
console.log(colors[0]); // Output: "red"
console.log(colors[2]); // Output: "blue"
console.log(colors.slice(2)); // Output: ["blue", "purple", "yellow"] (array of remaining colors)
type LoginInput: [string | number, string]; // Username/ID and password
let login: LoginInput = ["alice123", "secret"];
Mastering arrays and tuples in TypeScript equips you with powerful tools for managing ordered collections of data. By understanding their creation, manipulation, iteration, and advanced features, you can build robust and well-structured applications.Happy coding !❤️