Lesson 8 of 10

Arrays and tuples

Goal

A fixed length, and the original array stays put

01

Explanation

The type number[] is an array of numbers of any length. A tuple like [string, number] has a fixed length and a type for each position: the first element is a string and the second is a number.

The compiler doesn't infer tuples on its own. [["Layan", 82]] is inferred as (string | number)[][], and the difference between the name and the score is lost.

The type readonly Entry[] is a read-only array: it has no push, no sort, and no other method that changes the array itself. Use it for function parameters that have no business changing what they receive.

This catches a common mistake: sort sorts the original array in place and returns that same array, so the caller's data gets reordered without anyone asking for it. The fix is to copy it first: [...entries].sort(...).

02

Your task

Define type Entry = [string, number] and make it the element type of board. Make the parameter of ranked a readonly Entry[], and have the function return a copy sorted by score from highest to lowest, leaving the original array unchanged.

Checks

6 checks
  1. No type errors
  2. Entry is a tuple of a string followed by a number
  3. Entry rejects the reverse order
  4. The compiler knows the element types of board
  5. ranked accepts a read-only array
  6. ranked sorts a copy and leaves the original alone
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.