Open In App

TypeScript Object The Array Type

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Array Type
let fruits: string[] = 
    ["apple", "banana", "cherry"];
  
// Add a new fruit to the array
fruits.push("orange");
  
// Access elements by index
console.log(fruits[0]); // Outputs: "apple"
  
// Iterate through the array
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




// Array Type
let numbers: number[] = [1, 2, 3, 4, 5];
  
// Calculate the sum of all numbers in the array
let sum = 0;
for (const num of numbers) {
    sum += num;
}
  
// Outputs: Sum of numbers: 15
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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads