Lesson 4 / 1233%

Lesson 4

Arrays and Tuples

18 min

Type arrays, use tuples and protect data with readonly.

What is an array? What is a tuple?

Definition

An array is an ordered collection of values, where each value is identified by its position (its index, which starts at 0). A tuple is a special kind of array whose length is fixed and whose positions each have their own type.

Almost every program handles lists: the grades of a class, the items in a cart, the results of a search. TypeScript lets you describe precisely what a list contains, so that the editor helps you write correct code and warns you as soon as a value doesn't fit.

Typing an array

To type an array, you add square brackets [] after the type of the elements. All the elements must then have that type. So number[] reads as "array of numbers" and string[] as "array of strings".

arrays.ts
const grades: number[] = [12, 15, 9, 18];
const firstNames: string[] = ["Lea", "Tom", "Sara"];

grades.push(14);          // OK
grades.push("fourteen");  // Error: string is not assignable to number

// Equivalent notation using the generic syntax
const cities: Array<string> = ["Lyon", "Lille"];
Diagram of an array: an ordered collection of values, each identified by its index starting at 0.

The two notations number[] and Array<number> are strictly equivalent. The first, shorter one is the most common; the second becomes useful with more complex types.

Reading an element and looping over an array

You access an element with its index between square brackets. TypeScript then knows that the resulting value has the type of the array's elements, and you can use it directly. To go through all the elements, the for...of loop also keeps this type.

looping.ts
const grades: number[] = [12, 15, 9, 18];

const first = grades[0];     // number
console.log(grades.length);  // 4

for (const grade of grades) {
  console.log(grade.toFixed(1)); // grade is a number
}

Array methods benefit from types

TypeScript propagates types through methods like map or filter. In a function passed to map, you have nothing to annotate: the type of each element is already known, and the type of the result is computed automatically.

methods.ts
const prices: number[] = [10, 20, 30];

const withTax = prices.map((p) => p * 1.2);             // number[]
const expensive = prices.filter((p) => p > 15);         // number[]
const labels = prices.map((p) => "Item " + p);          // string[]
const total = prices.reduce((sum, p) => sum + p, 0);    // number

Arrays with several types

To accept several types in the same array, you use a union, in parentheses (we will go deeper into unions in a later lesson). The parentheses matter: string | number[] would mean "a string, or an array of numbers".

mixed.ts
const data: (string | number)[] = ["Lea", 25, "Lyon", 1];

Modifying an array

Methods that modify an array also respect the type of the elements: push and unshift add, pop and shift remove. Be careful, pop can return undefined when the array is empty, and TypeScript takes this into account in the type of the result.

modifying.ts
const cart: string[] = ["apple"];

cart.push("pear");          // OK
cart.unshift("banana");     // OK, added at the beginning
const last = cart.pop();    // string | undefined

cart.includes("apple");     // true
cart.includes(42);          // Error: number is not assignable to string

Tuples

A tuple is an array whose length and the type of each position are fixed. It is ideal for grouping a small number of related values, such as coordinates or a key-value pair.

Diagram of a tuple: a fixed length, with each position having its own type.
tuples.ts
let person: [string, number] = ["Lea", 25];

console.log(person[0]); // "Lea" (string)
console.log(person[1]); // 25 (number)

person = [25, "Lea"];    // Error: wrong order of types
person = ["Tom"];         // Error: an element is missing

// Labeled tuple for better readability
let point: [x: number, y: number] = [4, 7];

Tuples work very well with destructuring, which lets you give a name to each position. This is exactly the mechanism you will meet later with state management functions in web frameworks.

destructuring.ts
const [userName, age] = person;  // userName: string, age: number

function minMax(values: number[]): [number, number] {
  return [Math.min(...values), Math.max(...values)];
}

const [smallest, largest] = minMax([3, 8, 1]);

Going further with tuples

A tuple position can be made optional with a question mark, and the end of a tuple can accept a variable number of elements thanks to the ... syntax. These variants stay rare at the beginning, but they show the flexibility of the type system.

advanced-tuples.ts
let identity: [string, number?] = ["Lea"];    // optional age
identity = ["Tom", 30];                         // OK

let result: [string, ...number[]] = ["math", 12, 15, 9];
  • Array: variable number of elements, all of the same type (or of a union).
  • Tuple: fixed number of elements, each position has its own type.

Read-only arrays

With the readonly keyword, you forbid any modification of the array after it is created. It is good protection when an array is shared between several parts of the code.

readonly.ts
const days: readonly string[] = ["monday", "tuesday", "wednesday"];

days.push("thursday"); // Error: push does not exist on a readonly array

Good to know

An array declared empty, like const list = [], is poorly typed in strict mode: TypeScript can't know what it will contain. Always specify its type:const list: string[] = [].

Warning

When you write const point = [4, 7] without an annotation, TypeScript infers a regular number[] array, not a tuple. If you want a tuple, annotate it: const point: [number, number] = [4, 7]. Without that, nothing prevents adding a third element with push.

In short, choose an array for a list whose size may change (grades, items), and a tuple for a small group of values of different natures whose order has a meaning (a coordinate, a name-age pair). If the group grows or if the positions become hard to remember, an object with named fields will be more readable: we will see that soon.

Summary

  • You type an array with type[] or Array<type>.
  • Methods like map and filter infer types automatically: no need to annotate their parameters.
  • A mixed array is declared with a union in parentheses: (string | number)[].
  • A tuple fixes the length and the type of each position.
  • readonly protects an array against any modification.

Exercise

Create an array of numbers representing grades, then compute the average with reduce and display the grades above the average with filter. Check that TypeScript refuses the addition of a string.

Going further

Write a function that returns the smallest and the largest element of an array of numbers as a [number, number] tuple.