TypeScript

TypeScript Array Type

In this tutorial, you’ll learn about the TypeScript array type and its basic operations.

Introduction to TypeScript array type

A TypeScript array is an ordered list of data. To declare an array that holds values of a specific type, you use the following syntax:

let arrayName: type[];

For example, the following declares an array of string:

let names: string[];

And you can add one or more strings to the array:

names[0] = "Narayana";
names[1] = "Selvan";

or use the push() method:

names.push('Kumar');

The following declares a variable and assigns an array of strings to it:

let names = ['Narayana','Selvan','Kumar'];

In this example, TypeScript infers the skills array as an array of strings. It is equivalent to the following:

let names: string[];
names = ['Narayana','Selvan','Kumar'];

Once you define an array of a specific type, TypeScript will prevent you from adding incompatible values to the array.

The following will cause an error:

names.push(100);

… because we’re trying to add a number to the string array.

Error:

Argument of type 'number' is not assignable to parameter of type 'string'.

When you extract an element from the array, TypeScript can do type inference. For example:

let name = names[0];
console.log(typeof(name));

Output:

string 

In this example, we extract the first element of the names array and assign it to the name variable.

Since an element in a string array is a string, TypeScript infers the type of the name variable to string as shown in the output.

TypeScript array properties and methods

TypeScript arrays can access the properties and methods of a JavaScript. For example, the following uses the length property to get the number of element in an array:

let series = [1, 2, 3];
console.log(series.length); // 3

And you can use all the useful array method such as forEach()map()reduce(), and filter(). For example:

let series = [1, 2, 3];
let doubleIt = series.map(e => e* 2);
console.log(doubleIt);

Output:

[ 2, 4, 6 ]

Storing values of mixed types

The following illustrates how to declare an array that hold both strings and numbers:

let scores = ['Programming', 5, 'Software Design', 4];

In this case, TypeScript infers the scores array as an array of string | number.

It’s equivalent to the following:

let scores : (string | number)[];
scores = ['Programming', 5, 'Software Design', 4]; 

Conclusion

  1. In TypeScript, an array is an ordered list of values. An array can store a mixed type of values.
  2. To declare an array of a specific type, you use the let arr: type[] syntax.

About the Author: Narayan selvan

I am a front-end developer.