HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TypeScript / TypeScript Array

TypeScript Array

A typescript array can store multiple values of different data types sequentially, similar to other programming languages.

In this post, we will learn to create an 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

1. Creating a TypeScript 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 the 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.

//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];



let flags: boolean[] = [false, false, true];	

//or

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



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

//or

let scores: 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'.

2. Iterating through an Array

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

2.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.

2.2. 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
}

3. Cloning an Array

Use spread operator to clone 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"

4. Merging two 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 the comments section.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

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 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

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)