How to create and manipulate TypeScript arrays
Static typing makes it possible for the TypeScript compiler to monitor the data type of array elements. This feature helps TypeScript arrays to reduce the likelihood of errors in your code, allowing you to develop safer and more reliable applications.
What are TypeScript arrays?
In TypeScript, arrays are ordered lists of values. Just like in JavaScript, you can use arrays in TypeScript to store a collection of elements. Elements can belong to different data types, including numbers, strings, objects or other arrays. TypeScript has the advantage of supporting static typing, which means that you can specify the data type of the elements in an array. This, in turn, improves error detection during development.
A key feature of arrays is their dynamic size, which allows you to add or remove elements without having to determine the size in advance. In TypeScript, arrays are mutable by default. However, you can create immutable arrays by using array methods such as map
and filter
. Immutable arrays can be used to create new arrays based on existing arrays. Arrays provide a consistent structure for organising data and make it easier to filter, sort and iterate over elements.
In addition, TypeScript arrays can provide a basis for implementing data structures such as stacks (LIFO - Last-In-First-Out) and queues (FIFO - First-In-First-Out). They are also suitable for representing lists, tables and collections in a variety of applications. Because elements belonging to the same type can be easily managed, arrays are particularly useful when processing data from external sources, be it APIs or databases.
What is the syntax for TypeScript arrays?
In TypeScript, arrays are declared with the keywords let
, const
or var
followed by a variable name and a data type specification. When you declare a data type, you specify which data type the elements in the array should have. This is done using a colon. The elements are placed in square brackets and separated by commas in an array initialiser block.
The general syntax for declaring a TypeScript array is as follows:
const variableName: datatype[] = [element1, element2, ...];
typescript- variableName is the name you choose for the array.
- datatype specifies the data type of the elements in the array.
- [element1, element2, …] are the actual elements or values that are to be stored in the array. These elements should have the data type that has been specified for the array.
Here are a few examples that help to illustrate the syntax:
// Data type: Number
const numbers: number[] = [1, 2, 3, 4, 5];
// Data type: String
const numbers: string[] = ["Alice", "Bob", "Charlie"];
// Data type: Boolean
const booleans: boolean[] = [true, false];
typescriptWhat TypeScript array methods are there?
TypeScript array methods are extremely useful and powerful because they allow you to efficiently process, transform and organise data into arrays. The following table gives you an overview of common array methods in TypeScript and how they can be used.
Methods | Description |
---|---|
push()
|
Adds one or more elements to the end of the array and returns the new length of the array. |
pop()
|
Removes the last element from the array and returns it. |
unshift()
|
Adds one or more elements to the beginning of the array and returns the new length of the array. |
shift()
|
Removes the first element from the array and returns it. |
concat()
|
Combines the current array with one or more other arrays and returns a new array. The original array remains unchanged. |
join(separator)
|
Converts the elements of the array into a string and returns it. You can decide on a separator for the elements. |
slice(start, end)
|
Creates a flat copy of the array consisting of the elements between the specified indices ‘start’ (inclusive) and ‘end’ (exclusive). The original array remains unchanged. |
splice(start, deleteCount, element1, element2, ...)
|
Inserts new elements at the specified position and/or removes elements from the array. |
forEach(callback)
|
Executes a provided function for each element in the array. |
map(callback)
|
Creates a new array by applying a function to each element in the array. |
filter(callback)
|
Creates a new array with all elements that pass the test implemented by the specified function |
TypeScript array examples
TypeScript arrays are indispensable tools when it comes to organising and processing data in applications. We’ll take a look at some of the key operations below.
Accessing array elements
Accessing array elements in TypeScript is a basic operation that allows you to retrieve specific elements within an array. You can access array elements using their index, which represents their position in the array. In TypeScript, array indexes are zero-based. This means that the first element has index 0 and the second element has index 1.
let myArray: number[] = [10, 20, 30, 40, 50];
// Accessing elements using index
let firstElement: number = myArray[0]; // Output: 10
let secondElement: number = myArray[1]; // Output: 20
let thirdElement: number = myArray[2]; // Output: 30
// Assigning a new value to an array element
myArray[3] = 99; // 4th element in myArray = 99
typescriptDestructuring arrays
With array destructuring, you can quickly and easily extract values from an array and assign them to a variable.
let numberArray: number[] = [1, 2, 3];
// Array destructuring
let [firstNumber, secondNumber, thirdNumber] = numberArray;
// Access values
console.log(firstNumber); // Outputs 1
console.log(secondNumber); // Outputs 2
console.log(thirdNumber); // Outputs 3
typescriptIterating over elements in TypeScript arrays
Here is an example of how to iterate over an array in TypeScript using a for loop:
let numbers: number[] = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
typescriptIn this example, we have the numbers
array, which contains numbers. We use a for loop to iterate through the array. The loop starts at i = 0
, and we increment i
in each loop pass. With numbers[i]
we are able to access the respective element of the array and output it.
This is the output:
1
2
3
4
5
typescript- Free website protection with SSL Wildcard included
- Free private registration for greater privacy
- Free 2 GB email account
![](https://www.ionos.co.uk/digitalguide/fileadmin/DigitalGuide/IAS/CTAs/SEO_Digital_Guide_Mobile_nur-Nlement_900x750.png)