Arrays & Tuples — TypeScript

An array gets the type string[], number[] or Array<string>: one kind of item, any number of them, and an item of another type is rejected (ts(2345)). A tuple…

The playlist on your phone holds one kind of thing: all songs, and you can keep adding to it. A row on an attendance sheet is different. It always has the same columns, in the same order: the first column is the name, the second is the age. Both shapes of data appear in code all the time, and TypeScript has a type for each.

The playlist is a picture of an array: a list where every item is the same kind of thing. An array's type matches what it holds: string[] means an array where every item is text, however many there are. The attendance row is a picture of a tuple: an array with a fixed number of items, where each position has its own type, like each column in the attendance row. For example, [string, number] for a name and an age.

Array: a list of one kind of thing

Each of the three variables below holds an array. The last two lines try to add items to fruits:

let fruits: string[] = ["apple", "orange", "mango"];
let scores: number[] = [1, 2, 3];
let names: Array<string> = ["Budi", "Ani"];

fruits.push("banana"); // allowed
fruits.push(5);

Taking the first item in a function

The function getFirst takes an array of text and returns its first item:

function getFirst(arr: string[]): string {
  return arr[0];
}

console.log(getFirst(["x", "y", "z"])); // x
console.log(getFirst(fruits));          // apple

Tuple: a fixed count and order

profile below is a tuple that holds a name and an age. The last two lines are wrong on purpose:

let profile: [string, number] = ["Budi", 17];

let studentName = profile[0]; // string
let age = profile[1];         // number
let other = profile[2];
profile = [17, "Budi"];

A plain array is different. If fruits holds three pieces of text, ["apple", "orange", "mango"], then fruits[3] is still accepted, with the type string. But when the code runs, it holds undefined. The reason: the type of a plain array doesn't record its length. Only a tuple knows how many items it has.

readonly: you can read it, not change it

The word readonly before an array type means the array can only be read. The last two lines below try to change it:

const COLORS: readonly string[] = ["red", "blue"];

COLORS[0];                       // reading is fine: "red"
COLORS.map((c) => c + "!");      // fine, it makes a new array
COLORS.push("green");
COLORS[0] = "black";

const and readonly are different: const stops the variable from being given another array, readonly stops the array's items from being changed.

⚠️ Brackets in the wrong place, and a tuple you can still push to

TL;DR: An array gets the type string[], number[] or Array<string>: one kind of item, any number of them, and an item of another type is rejected (ts(2345)). A tuple, such as [string, number], is an array with a fixed count and its own type at each position. An index past a tuple's length is rejected (ts(2493)), while a plain array accepts an index past its length, and when the code runs that item is undefined. readonly string[] is an array that can be read and mapped, but push and replacing items are rejected. readonly is only checked before the code runs. To return the first item of the array sent in through the parameter arr, write return arr[0];.

⚡ Array: one kind of thing

Write:

let fruits: string[] = ["apple", "orange", "mango"];

fruits.push("banana"); // allowed
fruits.push(5);

Meaning: string[] is the type of an array where every item is text, however many there are. So fruits.push(5) is rejected. Careful, [string] is different: that's a tuple (an array with a fixed number of items) holding exactly one piece of text.

⚡ Tuple: a fixed count and order

Write:

let profile: [string, number] = ["Budi", 17];

let other = profile[2];
profile = [17, "Budi"];
Guess first: the tuple [string, number] holds exactly two items, at positions 0 and 1. Does TypeScript accept profile[2]?

Rejected: Tuple type '[string, number]' of length '2' has no element at index '2'. A tuple knows how many items it has. A plain array doesn't. If fruits holds only three pieces of text, fruits[3] is still accepted, even though it holds undefined.

Meaning: [string, number] means exactly 2 items: position 0 is text, position 1 a number. The order is checked too, so [17, "Budi"] is rejected.

⚡ readonly: read it, don't change it

Write:

const COLORS: readonly string[] = ["red", "blue"];

COLORS[0];            // allowed
COLORS.push("green");

Meaning: readonly before an array type means the array can only be read. Methods that change an array, like push, aren't available on a readonly array. const stops the variable from getting a different array, readonly stops the array's contents from changing.

What you will learn