Page Content

Tutorials

What is the type definition of Array in TypeScript?

Array in TypeScript

An array is a unique type of object used in TypeScript and JavaScript for organising a set of values or a sequence. Array types, like arrays of texts or klos, are typically made to be homogenous, which means that every element has the same type.

TypeScript supports two equivalent ways to declare the type of an array: the shorthand notation, T[], and the use of the generic Array<T> interface.

You might use either form, for instance, to declare a variable called threePigs as an array of numbers:

let threePigs: number[] = [9-11];
let genericStringArray: Array<string> = ['first', '2nd', '3rd'];

The performance and meaning of both syntaxes are the same. Nonetheless, the highly advise using a particular norm to improve readability and clarify intent.

Typing Arrays

Instead of using the generic syntax foos: Array, the style guide’s predominant proposal is to annotate arrays using the shorthand notation foos: Foo[].

There are multiple explanations for this preference:

  1. It’s more readable.
  2. The TypeScript team uses it as a standard.

Because the mind is taught to notice [], the notation makes it easy for the reader to recognise that the item is an array right away.

Tuples 

An ordered list of elements is represented using a tuple type, which is a TypeScript subtype of the fundamental Array type. In contrast to ordinary arrays, which are made to store a variable number of elements of a single type or a union of types, tuples are distinguished by two features:

  1. The number of elements they include is fixed.
  2. The values at each index represent a heterogeneous collection and have distinct, known categories.

Although developers typically use arrays instead of first-class tuples in JavaScript, the TypeScript type system specifically allows them. The syntax : [typeofmember1, typeofmember2] is used to annotate tuples.

You can specify a pair of strings and numbers, for example, as a tuple with known, distinct types:

// Tuple Declaration: [string, number]
var nameNumber: [string, number]; 
nameNumber = ['Jenny', 8675309]; // Okay

// Error Example (Type mismatch)
// nameNumber = ['Jenny', '867-5309']; // Error! '867-5309' is not assignable to 'number' 

// Example accessing elements:
let day: [number, string]; 
day = [0, 'Monday']; // valid 
console.log(day); // 0 
console.log(day[9]); // Monday 

Output (Simulated Console for Tuple Access):

0
Monday

Because tuples are functionally changeable, you can change their elements after they’ve been declared. Additionally, tuples can be used to set minimum lengths or optional trailing components by utilising optional elements (?) and remainder elements (…string[]).

Array Destructuring

The term “destructuring” describes the actual dismantling or “de-structuring” of an entity, a feature that TypeScript (and ES6) offer. It is thought of conceptually as the opposite of using an object literal to structure an object.

Array destructuring enables you to separate values from arrays or array-like structures (such as tuples) into discrete variables, frequently completing tasks that would otherwise take many lines.

Swapping the values of two variables without the need for a third temporary variable is a prime example of array destructuring in action.

// Code: Array Destructuring for swapping
var x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);

Output:

2 1

In essence, this method involves the compiler taking care of element access (`,, etc.) automatically on your behalf. Temporary variables (such as_a`) are created by the compiler to manage this swap when targeting older JavaScript versions (non-ES6).

Particularly with tuples, destructuring makes them appear very “first class” while being arrays at their core.

Destructuring with Rest Elements and Ignores

Within the destructuring assignment, you can use the remainder operator () to gather all of the remaining elements into a new array after capturing a predetermined amount of elements from the beginning of an array:

// Code: Array Destructuring with Rest
var [x, y, ...remaining] = ;
console.log(x, y, remaining);

Output:

1 2

Certain members in the array can also be ignored by simply leaving their corresponding location in the left-hand side assignment empty, denoted by commas (e.g., [x,,…remaining]).

// Code: Array Destructuring with Ignores
var [x, , ...remaining] = ;
console.log(x, remaining);

Output:

1

Loops 

TypeScript (and ES6) introduces the for…of loop, a contemporary iteration construct that iterates directly across an iterable object’s items or members.

This technique fixes the for…in loop being incorrectly utilised for arrays, a typical mistake made by novice JavaScript developers. The for…in loop iterates over an object’s keys (indices), including arrays, rather than its values.

The for…of loop guarantees that array members are iterated over correctly:

// Code: Comparing for...in vs. for...of
var someArray = ;

console.log("Using for...in (Iterates keys):");
for (var item in someArray) {
    console.log(item); 
}

console.log("Using for...of (Iterates members):");
for (var item of someArray) {
    console.log(item); 
}

Output:

Using for...in (Iterates keys):
0
1
2
Using for...of (Iterates members):
9
2
5

For iterating through a string character by character, the for…of loop also functions well.

The primary benefits of using for…of are that it eliminates the need for boilerplate code by avoiding the manual setup and management of an index variable and clarifies the objective. When targeting pre-ES6 environments, the TypeScript compiler automatically translates the for...of loop into a standard index-based for loop (for (var _i = 0; _i < someArray.length; _i++)).

Limitations: For legacy JavaScript targets (pre-ES6), for...of relies on the assumption that the object has a length property and can be indexed via numbers (e.g., obj). Therefore, for these legacy environments, it is officially supported only on string and array types. If TypeScript detects you are trying to use for...of on a type it cannot iterate (like a NodeList in older environments), it will issue a clear error.

Index