top of page

Introduction to TypeScript Array

TypeScript is a popular programming language that is widely used for web development. One of the key features of TypeScript is its support for arrays. In this article, we will take a closer look at TypeScript arrays and explore their features, syntax, and capabilities.


What is a TypeScript Array?

A TypeScript array is an ordered collection of elements of the same type. Arrays in TypeScript can be declared using the array literal notation ([]) or the Array constructor function. The Array constructor takes an optional parameter that specifies the length of the array, while the array literal notation allows you to initialize the array with values.


Syntax:

The syntax for declaring an array in TypeScript using the array literal notation is as follows:

let arrayName: dataType[] = [value1, value2, value, ...];

The syntax for declaring an array in TypeScript using the Array constructor is as follows:

let arrayName = new Array(length);

where 'length' specifies the number of elements in the array.


Accessing Array Elements

In TypeScript, array elements can be accessed using their index. The index of the first element in the array is zero, and the index of the last element is the length of the array minus one. You can access an array element using the following syntax:

arrayName[index];

Iterating Through an Array:

You can iterate through an array in TypeScript using a for loop, a for...of the loop, or a forEach loop. Here is an example of iterating through an array using a for loop:

let fruits: string[] = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) 
{ 
    console.log(fruits[i]); 
}

Here is an example of iterating through an array using a for...of the loop:

let fruits: string[] = ['apple', 'banana', 'orange'];
for (let fruit of fruits) 
{ 
    console.log(fruit); 
}

And here is an example of iterating through an array using a forEach loop:

let fruits: string[] = ['apple', 'banana', 'orange'];
fruits.forEach(function(fruit) 
{ 
    console.log(fruit); 
});

Also read:

Adding and Removing Elements

In TypeScript, you can add or remove elements from an array using various methods. The push() method adds one or more elements to the end of the array, while the pop() method removes the last element from the array. The unshift() method adds one or more elements to the beginning of the array, while the shift() method removes the first element from the array. The splice() method can be used to add, remove, or replace elements at any position in the array.


Here is an example of adding elements to an array using the push() method:

let fruits: string[] = ['apple', 'banana'];
fruits.push('orange', 'kiwi');
console.log(fruits); 

// Output: ['apple', 'banana', 'orange', 'kiwi']

Here is an example of removing elements from an array using the pop() method:

let fruits: string[] = ['apple', 'banana', 'orange'];
fruits.pop();
console.log(fruits); 

// Output: ['apple', 'banana']

Here is an example of adding elements to an array using the unshift() method:

let fruits: string[] = ['apple', 'banana'];
fruits.unshift('orange', 'kiwi');
console.log(fruits); 

// Output: ['orange', 'kiwi', 'apple', 'banana']

Here is an example of removing elements from an array using the shift() method:

let fruits: string[] = ['apple', 'banana', 'orange'];
fruits.shift();
console.log(fruits); 

// Output: ['banana', 'orange']

Here is an example of using the splice() method to add elements to an array:


let fruits: string[] = ['apple', 'banana', 'orange'];
fruits.splice(1, 0, 'kiwi', 'mango');
console.log(fruits); 

// Output: ['apple', 'kiwi', 'mango', 'banana', 'orange']

Here is an example of using the splice() method to remove elements from an array:


let fruits: string[] = ['apple', 'banana', 'kiwi', 'mango', 'orange'];
fruits.splice(2, 2);
console.log(fruits); 

// Output: ['apple', 'banana', 'orange']

Sorting and Searching Arrays

In TypeScript, you can sort and search arrays using various methods. The sort() method sorts the elements of an array in ascending or descending order. The indexOf() method searches for the first occurrence of a specified element in an array and returns its index. The lastIndexOf() method searches for the last occurrence of a specified element in an array and returns its index.


Here is an example of sorting an array in ascending order:

let fruits: string[] = ['banana', 'apple', 'orange', 'kiwi'];
fruits.sort();
console.log(fruits); 

// Output: ['apple', 'banana', 'kiwi', 'orange']

Here is an example of sorting an array in descending order:

let fruits: string[] = ['banana', 'apple', 'orange', 'kiwi'];
fruits.sort((a, b) => b.localeCompare(a));
console.log(fruits); 

// Output: ['orange', 'kiwi', 'banana', 'apple']

Here is an example of using the indexOf() method to search for an element in an array:

let fruits: string[] = ['apple', 'banana', 'orange'];
let index = fruits.indexOf('banana');
console.log(index); 

// Output: 1

Types of Array in Typescript

There are 4 different types of arrays in Typescript:

  1. Basic Array

  2. Tuple Array

  3. Multi-dimensional Array

  4. Readonly Array

1. Basic Array

The most common type of array in TypeScript is a basic array, also known as a homogeneous array. It is an ordered collection of elements of the same data type. To declare a basic array in TypeScript, you can use the following syntax:

let numbers: number[] = [1, 2, 3, 4, 5];
let strings: string[] = ["Hello", "World"];

In the above code snippet, we have declared two arrays, numbers and strings, of type number and string, respectively. The values of the arrays are initialized using array literals.


2. Tuple Array

A tuple array is an array that contains elements of different data types. It is also known as a heterogeneous array. To declare a tuple array in TypeScript, you can use the following syntax:

let person: [string, number] = ["John", 30];

In the above code snippet, we have declared a tuple array person that contains two elements, a string and a number. The order of the elements is important, and the number of elements must match the tuple type.


3. Multi-dimensional Array

A multi-dimensional array is an array that contains one or more arrays as its elements. It is also known as a jagged array. To declare a multidimensional array in TypeScript, you can use the following syntax:

let matrix: number[][] = [[1, 2], [3, 4], [5, 6]];

In the above code snippet, we have declared a multi-dimensional array matrix that contains three sub-arrays, each containing two elements. The elements of the sub-arrays can be accessed using the index of the sub-array and the index of the element within the sub-array.


4. Readonly Array

A readonly array is an array that cannot be modified after it is created. It is useful when you want to ensure that the elements of an array remain constant throughout the execution of your program. To declare a readonly array in TypeScript, you can use the following syntax:

let numbers: ReadonlyArray<number> = [1, 2, 3, 4, 5];

In the above code snippet, we have declared a readonly array of numbers of type number. Once the array is created, its elements cannot be modified.


Advantages of TypeScript Array:

  1. TypeScript arrays allow you to declare the data type of the array elements. This helps catch errors at compile-time rather than run-time.

  2. With TypeScript, you can write cleaner and more readable code by using interfaces and generics. This can help improve the overall quality of your code.

  3. TypeScript offers better tooling support than plain JavaScript, which includes better code completion, error checking, and debugging.


Disadvantages of TypeScript Array:

  1. TypeScript adds additional complexity to your code, which can be challenging for beginners to learn.

  2. Because of the strong typing and additional complexity, TypeScript code can take longer to write and debug.

  3. If you are using third-party libraries, there may be compatibility issues with TypeScript, as not all libraries are written in TypeScript.


Conclusion

Arrays are data structures in TypeScript that allow you to store and manipulate collections of elements. Whether you need a basic array, tuple array, multi-dimensional array, or readonly array, TypeScript provides a variety of options to suit your needs. By understanding the different types of arrays and how to use them, you can write more maintainable and error-free code.


Also read:
0 comments

Recent Posts

See All

Comments


bottom of page