TypeScript Arrays: Initialization And Common Methods

TypeScript arrays

TypeScript arrays look and behave in basically the same way as their JavaScript counterparts. Still, there are some critical differences you must be aware of. Read on to learn more about them.

TypeScript Arrays Vs. JavaScript Arrays

Arrays are a collection of items that can be referred to by a single name. In JavaScript, you can use them to hold data of multiple types. It doesn’t even require you to declare those types beforehand and adhere to them.

This is a valid and common use of arrays in JavaScript:

let site = ['learnshareit', 2022, true'];

While the statement above is also legal and will be compiled without errors in TypeScript, this practice isn’t recommended.

TypeScript encourages developers to use homogeneous arrays. This means explicitly declaring the data type for the whole array and sticking with it throughout the program. You shouldn’t mix various data types into a single array. Otherwise, you will have a harder time achieving type safety.

Typed arrays are available in JavaScript too, but they are cumbersome and aren’t as seamless as TypeScript arrays.

Array Initialization

The syntax for array declaration and initialization is basically the same between TypeScript and JavaScript. To form an array literal, you still use commas to separate items in an array and brace brackets to enclose them.

But TypeScript allows you to specify which type the array items should hold:

let site: string[];
site = ['learnshareit', 'quora', 'reddit'];

The first statement is an array declaration, and it requires no initial value. It starts off as undefined and can be given a new value later.

By using type annotation, you can tell TypeScript that site is an array whose items are string values. This is done by naming the type followed by a pair of square brackets.

You can also class generics to define the type of an array. Their syntax looks like this: Array<type>:

let site: Array<string>;
site = ['learnshareit', 'quora', 'reddit'];

While they mean basically the same thing, most still prefer the bracket syntax because of its simplicity.

When you don’t include type annotation but give an array some initial values, TypeScript will infer the type from these elements:

let numberArray = [1];
numberArray[1] = 'a';

Output:

Type 'string' is not assignable to type 'number'.

In this example, TypeScript automatically sets the type of the array numberArray to number. Any attempt to assign values of other types to its element will result in errors.

Accessing Array Elements

TypeScript arrays aren’t associative arrays and you have to access their elements through their indexes. In particular, we use nonnegative integers. Arrays are zero-indexed, so the first element is at index 0, the second index, and so on. The last item of an array has the length of the array minus 1 as its index.

Use the square brackets to access elements of an array:

let colors: string[] = ['orange', 'blue', 'green', 'black'];
console.log(colors[2]);

Output:

green

TypeScript doesn’t support negative indexes. Doing so doesn’t lead to errors, but you will receive the undefined value instead of the item you are looking for.

Arrays Of Union Types

TypeScript allows you to create new types from existing ones, such as primitive types (string, number, and boolean).

Using union types, you can combine multiple them together and use them with your arrays. This way, you can still store multiple types in your array in a safe way and take advantage of type checking in TypeScript.

You can form a union type by using the pipe character to separate the member types:

let site: (string | number)[];

This example creates an array whose item can be either a string or a number. TypeScript understands the union type string | number, accepting all possible values of type string and type number.

After this declaration, you can add values to the array:

site = ['learnshareit', 1, 'TypeScript'];

Remember that the parentheses are important when declaring a union type for arrays. The meaning of the union type would be significantly different without them:

let site: string | number[];
site = ['learnshareit', 1, 'TypeScript'];

Output:

typescript.ts:2:1 - error TS2322: Type '(string | number)[]' is not assignable to type 'string | number[]'.
  Type '(string | number)[]' is not assignable to type 'number[]'.
    Type 'string | number' is not assignable to type 'number'.
      Type 'string' is not assignable to type 'number'.

string | number[] creates a union type of strings and arrays of numbers, not arrays of strings and numbers. When you assign an array whose values aren’t numbers, the compiler detects errors in type compatibility.

Array Of The any Type

When you want your array to accept any type, you can use a special type in TypeScript: any.

This type means you can assign any value, access any property of the value, and do pretty much anything that is syntactically legal.

let anyArray: any[] = [];
anyArray[0] = true;
anyArray[1] = 1;
anyArray[2] = 'learnshareit';
console.log(anyArray);

Output:

[ true, 1, 'learnshareit' ]

Common Array Methods

You can use all JavaScript array instance methods in TypeScript.

The push() method

For example, the push() method adds elements to the end of an array and returns the length of the new array:

let colors: string[] = ['orange', 'blue', 'green', 'black'];
console.log(colors.push('white'));
console.log(colors);

Output:

5
[ 'orange', 'blue', 'green', 'black', 'white' ]

The pop() method

The pop() method removes the last element of an array:

console.log(colors);
colors.pop();
console.log(colors);

Output:

[ 'orange', 'blue', 'green', 'black', 'white' ]
[ 'orange', 'blue', 'green', 'black' ]

The concat() method

To merge two or more arrays, use the concat() method. It doesn’t change any existing array but instead returns the merging result in a new array:

let array1: number[] = [1, 2, 3];
let array2: number[] = [4, 5, 6];
let array3 = array1.concat(array2);
console.log(array3);

Output:

[ 1, 2, 3, 4, 5, 6 ]

The slice() method

TypeScript supports slicing via the slice() method. It returns a portion of an array from start to end positions, which are represented by indexes. Remember that slice() creates a shallow copy and returns it, not modifying the original array in any way.

let colors: string[] = ['orange', 'blue', 'green', 'black'];
console.log(colors.slice(1, 3));

Output:

[ 'blue', 'green' ]

The splice() method

If you want to change the contents of an array by modifying it directly, use splice(). It can delete or replace existing elements as well as add new elements to the elements without using a shallow copy.

This example uses splice() to delete one element from index 2 and insert the element ‘red’ in that position:

let colors: string[] = ['orange', 'blue', 'green', 'black'];
colors.splice(1, 1, 'red');
console.log(colors);

Output:

[ 'orange', 'red', 'green', 'black' ]

Tutorials

Learn more about TS Array in the article below:

Summary

Compared to JavaScript, TypeScript arrays provide better support for fixed data types. But you still have the option of storing values of different types into a single array. On top of that, you can utilize all array methods from JavaScript as usual in your code.

Leave a Reply

Your email address will not be published. Required fields are marked *