Lesson 4
18 min
Type arrays, use tuples and protect data with readonly.
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.
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".
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"];
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.
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.
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
}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.
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); // numberTo 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".
const data: (string | number)[] = ["Lea", 25, "Lyon", 1];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.
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 stringA 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.

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.
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]);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.
let identity: [string, number?] = ["Lea"]; // optional age
identity = ["Tom", 30]; // OK
let result: [string, ...number[]] = ["math", 12, 15, 9];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.
const days: readonly string[] = ["monday", "tuesday", "wednesday"];
days.push("thursday"); // Error: push does not exist on a readonly arrayGood 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.
type[] or Array<type>.(string | number)[].readonly protects an array against any modification.Exercise
reduce and display the grades above the average with filter. Check that TypeScript refuses the addition of a string.Going further
[number, number] tuple.