Start learning free

LESSON 264 OF 675 · TUPLES, SORTING & BUILT-INS

Tuples in TypeScript

Lesson

TL ; DR:

A tuple type like [string, number] describes a pair, like a movie's title and year. Destructuring unpacks it into variables in one line.


const movie: [string, number] = ["Frozen", 2013];   // a tuple

console.log(movie[0]);                              // Frozen

const [title, year] = movie;                        // destructuring

console.log(title + " " + year);                    // Frozen 2013

function firstAndLast(word: string): [string, string] {
    return [word[0], word[word.length - 1]];
}

const [first, last] = firstAndLast("code");

console.log(first + last);                          // ce


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. TypeScript keeps a pair like that in an array with a tuple type.

  • [string, number] is a tuple type. It has exactly two values, a string and then a number.
  • movie[0] is the first value, "Frozen". movie[1] is the second, 2013.
  • The type checks the values. ["Frozen", "2013"] is an error, and so is ["Frozen", 2013, 2014].

A plain (string | number)[] would allow any length and any order. The tuple type is stricter.

Destructuring gives each value its own name. Write the names in square brackets, in the same order as the values. After const [title, year] = movie;, title holds "Frozen" and year holds 2013. Their types come from the tuple type.

A function can return a tuple. Its return type is the tuple type, and return [a, b]; builds it.

Watch the count. A third name in const [a, b, c] = movie; is an error, because the tuple has only two values.


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make splitTime return its tuple: the whole hours and the minutes left.

Then destructure pet into name and age.

Last, call splitTime(135). Destructure its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check