TypeScript Object The Array Type
Last Updated :
02 Nov, 2023
In TypeScript, the Array Type is used to specify and enforce the type of elements that can be stored in an array, enhancing type safety during development. This adaptability ensures reusability across diverse data types, as exemplified by the Array type (e.g., number[] or string[]).
Syntax
let myArray: Type[] = [value1, value2, ...];
Parameters
- Type[]: This specifies the type of elements in the array.
- value1, value2, …: These are the values assigned to the array. The values should match the specified element type.
Example 1: In this example, we define an array of fruits of strings, add “orange, access elements by index (e.g., fruits[0]), and iterate through the array to log each fruit.
Javascript
let fruits: string[] =
[ "apple" , "banana" , "cherry" ];
fruits.push( "orange" );
console.log(fruits[0]);
for (const fruit of fruits) {
console.log(fruit);
}
|
Output
apple
apple
banana
cherry
orange
Example 2: In this example, we have an array numbers of type number holds values. A loop iterates to calculate the sum of these numbers, resulting in an output: Sum of numbers: 15.
Javascript
let numbers: number[] = [1, 2, 3, 4, 5];
let sum = 0;
for (const num of numbers) {
sum += num;
}
console.log( "Sum of numbers:" , sum);
|
Output:
Sum of numbers: 15
Example 3: In this example, interface data defines properties (name and age). An array of people holds objects adhering to the interface. A loop logs the name and age of each object.
Javascript
interface data {
name: string;
age: number;
}
const people: data[] = [
{ name: "Rohan" , age: 21 },
{ name: "Nikita" , age: 22 },
{ name: "Sumit" , age: 23 },
];
for (const data of people) {
console.log(`Name: ${data.name}, Age: ${data.age}`);
}
|
Output:
Name: Rohan, Age: 21
Name: Nikita, Age: 22
Name: Sumit, Age: 23
Reference: https://www.typescriptlang.org/docs/handbook/2/objects.html#the-array-type
Share your thoughts in the comments
Please Login to comment...