Design Converter
Education
Last updated on Feb 21, 2025
Last updated on Feb 21, 2025
How do you store multiple values in a single variable in TypeScript?
Arrays make it simple! They let you group related data, making your code cleaner and easier to manage. Whether you're working with numbers, strings, or objects, knowing how to initialize an array in TypeScript helps you write better programs.
This blog covers different ways to create arrays, access elements, and use built-in methods. You'll also learn how TypeScript ensures type safety while working with arrays.
Let's get started!
An array in TypeScript is a collection of values of the same data type stored under a single variable. The elements of an array can be accessed using their index, starting from zero.
TypeScript provides multiple ways to declare and initialize an array:
Using square brackets []
(Array literal)
Using the Array constructor
Using the generic array type Array<T>
Using the spread operator for merging two arrays
Each method has its advantages depending on the use case.
[]
(Simplest Form)This is the most commonly used approach for array declaration and initialization.
1let numbers: number[] = [1, 2, 3, 4, 5]; // Array with numeric values 2let fruits: string[] = ["Apple", "Banana", "Mango"]; // Array with string values
Here, all the elements in numbers are of numeric value, while fruits contains string values.
Another way to create an array is using the array constructor.
1let colors = new Array("Red", "Green", "Blue"); 2console.log(colors);
This method initializes a new array and assigns values.
<T>[]
The generic array type provides type safety and flexibility.
1let mixedArray: Array<number | string> = [1, "two", 3, "four"]; 2console.log(mixedArray);
This array allows storing different data types, ensuring type safety while maintaining flexibility.
If an array should start with predefined values, TypeScript allows setting static values.
1let defaultNumbers: number[] = new Array(5).fill(0); 2console.log(defaultNumbers); // Output: [0, 0, 0, 0, 0]
This initializes an array with one or more elements, all set to a default value.
To access values from an array, use the index notation.
1let numbers = [10, 20, 30, 40, 50]; 2console.log(numbers[0]); // First element 3console.log(numbers[numbers.length - 1]); // Last element
The first element is accessed using index 0, while the last element is retrieved using array.length - 1
.
To add elements, use the push() method.
1let cities = ["New York", "Los Angeles"]; 2cities.push("Chicago"); 3console.log(cities);
The push() method appends new values to the end.
To remove elements, use pop() or shift().
1let numbers = [10, 20, 30, 40]; 2numbers.pop(); // Removes last element 3console.log(numbers); 4 5numbers.shift(); // Removes first element 6console.log(numbers);
These methods adjust the new length of the array dynamically.
TypeScript provides several built-in array methods to work with arrays efficiently.
The map() function is useful for transforming an array.
1let numbers = [1, 2, 3]; 2let squaredNumbers = numbers.map(num => num * num); 3console.log(squaredNumbers); // Output: [1, 4, 9]
To extract specific array elements, use filter().
1let values = [10, 20, 30, 40, 50]; 2let filteredValues = values.filter(value => value > 25); 3console.log(filteredValues); // Output: [30, 40, 50]
The reduce() function helps in aggregation.
1let sum = [1, 2, 3, 4, 5].reduce((acc, num) => acc + num, 0); 2console.log(sum); // Output: 15
The spread operator helps merge two arrays.
1let array1 = [1, 2, 3]; 2let array2 = [4, 5, 6]; 3 4let mergedArray = [...array1, ...array2]; 5console.log(mergedArray);
Another way to merge arrays is by using concat().
1let combined = array1.concat(array2); 2console.log(combined);
To get the first element:
1let list = [100, 200, 300]; 2console.log(list[0]); // First element
To retrieve the last index:
1console.log(list[list.length - 1]); // Last element
Using toString() or join(), an array can be converted into a string representation.
1let fruits = ["Apple", "Banana", "Mango"]; 2console.log(fruits.toString()); // Output: Apple,Banana,Mango 3console.log(fruits.join(" - ")); // Output: Apple - Banana - Mango
To convert an array into a localized string, use toLocaleString().
1let dateArray = [new Date()]; 2console.log(dateArray.toLocaleString());
To extract elements from an array, use slice().
1let numbers = [10, 20, 30, 40, 50]; 2let sliced = numbers.slice(1, 4); 3console.log(sliced); // Output: [20, 30, 40]
Understanding how to initialize an array in TypeScript helps developers write cleaner and more maintainable code. Choosing the right approach makes it easier to manage data, improve readability, and optimize performance.
TypeScript offers multiple ways to create and modify arrays while ensuring type safety. Whether working with numbers, strings, or custom objects, these methods provide the flexibility needed for different use cases.
By applying these techniques, developers can build scalable applications with well-structured data handling.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.