HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TypeScript / Arrays in TypeScript

Arrays in TypeScript

Learn to create array, clone array, merge arrays and iterate through array elements in TypeScript with easy to follow examples.

Table of Contents

Create Array
Iterate Through Array
Clone Array
Merge Arrays

Create Array

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

Every time a new value is added to an array, the compiler checks for type compatibility and alerts if there is a type mismatch.

//array declaration and initialization in separate lines
let myArr1: boolean[];
let myArr2: boolean[] = [];
let myArr3: boolean[] = new Array();
let myArr4: boolean[] = Array();

myArr1 = [false, false, true];

//array inline declaration and initialization

//array of booleans	
let flags1: boolean[] = [false, false, true];	
//or
let	flags2: Array<boolean> =[false, false, true];

//array of numbers
let scores1: number[] = [10, 20, 30, 40];	
//or
let	scores2: Array<number> = [10, 20, 30, 40];	

Add elements to array

To add more elements to array, use push() method.

//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'.

Iterate Through Array

You can use either for...of loop or traditional for loop to iterate over array elements.

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.

Using traditional for loop

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

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

Clone Array

Use spread operator to clone array. It’s easiest and recommended way.

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

let clonedScores = [...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"

Merge Arrays

Use spread operator for merging arrays as well. It’s simplest and 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 comments section.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. RCR

    March 4, 2020

    what about an array of type class?

  2. jakk

    October 18, 2019

    I hate when they explain badly .. typescript sucks .. there is no information .. it makes no sense to explain array of one dimension .

  3. Tom Berend

    July 5, 2019

    how would I create a type for an array of vectors such as

    var myArray = [ [1,2,3], [2,3,4], [3,4,5] ]

  4. g8up

    February 15, 2019

    how to define the type of [ 1, ‘a’] ?

    • Lokesh Gupta

      February 15, 2019

      Arrays must be of similar data types. You cannot store integer and string inside single array.

      • Kumar Bitthal

        March 21, 2019

        Different data types can be stored provided the storing array is of type any, eg.

        array1: number[] = [1,2,3];
        arraystr: string[] = [“one”, “two”];
        array3: any[] = […this.array1, …this.arraystr];

Comments are closed on this article!

Search Tutorials

TypeScript Tutorial

  • TypeScript – Introduction
  • TypeScript – Types
  • TypeScript – Union Types
  • TypeScript – String Literal Types
  • TypeScript – var, let and const
  • TypeScript – Template Strings
  • TypeScript – Arithmetic Operators
  • TypeScript – Logical Operators
  • TypeScript – Comparison Operators
  • TypeScript – ‘for…of’ Loop
  • TypeScript – Spread Operator
  • TypeScript – Arrays
  • TypeScript – Enums
  • TypeScript – Map
  • TypeScript – Set
  • TypeScript – Functions
  • TypeScript – Function Overloading
  • TypeScript – Transpiler
  • TypeScript – Truthy and falsy
  • TypeScript – == vs ===
  • TypeScript – undefined vs null
  • TypeScript – Variable Hoisting
  • TypeScript – tsconfig.json

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces