TypeScript: Arrays
In TypeScript, an array is a data structure that allows you to store multiple values of the same type. An array is defined using square brackets []
and can contain any number of elements.
Here's an example of how to declare an array of numbers in TypeScript:
let numbers: number[] = [1, 2, 3, 4, 5];
In this example, the variable numbers
is declared as an array of numbers. The values inside the array are enclosed in square brackets and separated by commas.
You can also declare an array using the Array
keyword:
let numbers: Array<number> = [1, 2, 3, 4, 5];
This syntax is equivalent to the previous example.
Arrays can also be used with other data types, such as strings or objects:
let names: string[] = ["Alice", "Bob", "Charlie"];
let people: { name: string, age: number }[] = [ { name: "Alice", age: 30 }, { name: "Bob", age: 40 }, { name: "Charlie", age: 50 }];
You can access individual elements of an array using square brackets and the element's index:
let numbers: number[] = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Output: 1
console.log(numbers[2]); // Output: 3
You can also change the value of an element by assigning a new value to it:
let numbers: number[] = [1, 2, 3, 4, 5];
numbers[2] = 10;
console.log(numbers); // Output: [1, 2, 10, 4, 5]
Arrays have a number of built-in methods, such as push
, pop
, shift
, and unshift
, that allow you to add or remove elements from the array. You can also use methods like map
, filter
, and reduce
to perform more complex operations on the array.
let numbers: number[] = [1, 2, 3, 4, 5];
numbers.push(6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
let filteredNumbers = numbers.filter(n => n > 3);
console.log(filteredNumbers); // Output: [4, 5, 6]
Using any
as Array type
It is possible to use any
type for arrays. This allows us to have different types in one array like the example below:
let favoriteStuff: any[];
favoriteStuff = ['ball', 3, { age: 27, name: 'Sirius' }];
for (let i = 0; i < favoriteStuff.length; i++) {
console.log(i + ') ' + favoriteStuff[i]);
}
Console Output:
0) ball
1) 3
2) [object Object]
Looping Alternative
An alternative to the typical for loop
is as follows:
const person = {
name: 'Harry',
age: 22,
hobbies: ['basketball', 'ballet'],
};
for (const hobby of person.hobbies) {
console.log(hobby);
}
Console Output:
basketball
ballet
View Parent Post: TypeScript: Everything You Need to Know