TypeScript Array

Arrays in typescript are of fixed-length and homogeneous collection of values very similar to other programming languages. A typescript array can store multiple values of the same data types sequentially.

Arrays are always of fixed size. An array, once it is created, cannot be resized. Individual elements at various positions in the array are accessed via their index.

In this tutorial, we will learn to create an array, clone an array, merge arrays and iterate through the elements of an array in TypeScript with easy-to-follow examples.

1. Creating an Array

Like JavaScript, TypeScript has an Array type to allow the assignment of multiple values. The array is specified by adding a square bracket [] after the type.

To use the type-safety capability of TypeScript, we can add diamond brackets to specify the type of elements in the array. Every time a new value is added to such a generic array, the compiler checks for type compatibility and alerts if there is a type mismatch.

The following example declares a boolean array and then initializes its values.

//Various ways to declare a typed array
let myArr1: boolean[];
let myArr2: boolean[] = [];
let myArr3: boolean[] = new Array();
let myArr4: boolean[] = Array();

//Initializing an array
myArr1 = [false, false, true];

We can declare and initialize the array in the same line.

let flags: boolean[] = [false, false, true];	
//or
let flags: Array<boolean> = [false, false, true];

2. Adding an Item to Array

The push() method appends the given value at the last of an array and returns the size of the new array created as a result of push() operation.

It helps in treating the arrays as dynamic lists.

//array of numbers
let scores: number[] = [10, 20, 30, 40];

scores.push( 50 );	//[10, 20, 30, 40, 50]

scores.push( 'abc' );	 //data.ts(24,14): error TS2345: Argument of type '"abc"' is not
						//assignable to parameter of type 'number'.

See Also: Different ways to add items to Array and remove items from Array

3. Iterating Through Array Items

We can use either of for loops to iterate over array elements.

3.1. Using for…of Loop

let scores :number[] = [10, 20, 30, 40];	

for (var score of scores) {
	console.log(score);		//Outputs 10 20 30 40
}

DO NOT use “for…in” loop which is used to iterate over object attributes.

3.2. Using Traditional for Loop

let scores :number[] = [10, 20, 30, 40];	

for (var i = 0; i &lt; scores.length; i++) {
	console.log(scores[i]);		//Outputs 10 20 30 40
}

4. Cloning an Array

Use spread operator to clone the array. It is the easiest and the most recommended way.

let origScores: number[] = [10, 20, 30];	

let clonedScores: number[] = [...origScores];

console.log(clonedScores);		//[10, 20, 30]

origScores.push( 40 );

console.log(origScores);		//[10, 20, 30, 40] is "changed"
console.log(clonedScores);		//[10, 20, 30] 	is "unchanged"

5. Merging Two Arrays

Use spread operator for merging arrays as well. It’s the simplest and most recommended way.

let scores1: number[] = [10, 20, 30];
let scores2: number[] = [40, 50, 60];	

let mergedScore = [...scores1, ...scores2];

console.log(mergedScore);	//[ 10, 20, 30, 40, 50, 60 ]

Drop me your questions in the comments section.

Happy Learning !!

Comments

Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode