Tuples

Sometimes an array has a fixed number of elements, and each place in it has its own meaning: a position on a map is [x, y], an item with its count is ["Arrow", 20]. For such arrays, TypeScript has tuples: types that list the type of each element, in order:

const position: [number, number] = [3, 5];
const arrows: [string, number] = ["Arrow", 20];

console.log(`${arrows[0]} x${arrows[1]} at ${position[0]}, ${position[1]}`);

This prints:

Arrow x20 at 3, 5

[string, number] means exactly two elements: first a text, then a number. TypeScript knows the type of each of them: arrows[0] is a string and arrows[1] a number.

A tuple type has to be written as an annotation: from the values alone, TypeScript doesn't infer a tuple. From [3, 5] alone, TypeScript infers number[], an array of numbers of any length. From ["Arrow", 20], it infers (string | number)[], an array of any length whose elements can be texts or numbers in any order. (| means “or”; more in lesson 5.)

The order matters. When the values are swapped, TypeScript reports both of them:

const potion: [string, number] = [2, "Healing Potion"];
main.ts(1,35): error TS2322: Type 'number' is not assignable to type 'string'.
main.ts(1,38): error TS2322: Type 'string' is not assignable to type 'number'.

The length is fixed too. A pair has no third element, so TypeScript reports an attempt to read one:

const position: [number, number] = [3, 5];
console.log(position[2]);
main.ts(2,22): error TS2493: Tuple type '[number, number]' of length '2' has no element at index '2'.

In JavaScript, position[2] would quietly be undefined. When the program runs, a tuple is an ordinary JavaScript array, and console.log(arrows) prints ["Arrow", 20]. The tuple type only tells TypeScript what to check.

Typical mistakes:

  • A value with an extra element: const arrows: [string, number] = ["Arrow", 20, 5]; gives a message on two lines: Type '[string, number, number]' is not assignable to type '[string, number]'. and below it Source has 3 element(s) but target allows only 2. The second line explains the first one.
  • [number] instead of number[]: [number] is a tuple with exactly one number, number[] an array of any number of numbers.

Instructions

The values in the tuple potions are in the wrong order. Swap them, so that the program prints:

Healing Potion x2
Kira is at 3, 5

Give position the tuple type [number, number].

Kira walks two squares east. Just before the line that prints her position, add 2 to position[0], so that the program prints:

Healing Potion x2
Kira is at 5, 5

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/9