Lesson 3 of 11 · 8 min

Arrays and tuples

An array type is written with [] after the type of its items:

const scores: number[] = [72, 85, 90];
const names: string[] = ["Ana", "Tino"];

scores.push("ninety");   // error: string is not assignable to number

(Array<number> means the same as number[].)

TypeScript then knows the type of everything you do with the array: scores.map(s => s * 2) is a number[], and names[0].toUpperCase() is fine because each item is a string.

Tuples

Sometimes you want a small, fixed-size group where each position means something different. That is a tuple:

const point: [number, number] = [3, 4];
const entry: [string, number] = ["Ana", 30];

const [name, age] = entry;   // destructuring: name is string, age is number

Tuples are handy for returning two values from a function:

function divide(a: number, b: number): [number, number] {
  return [Math.floor(a / b), a % b];   // [quotient, remainder]
}

The spread ... turns an array into separate arguments: Math.max(...[3, 8, 2]) is Math.max(3, 8, 2).

Your task

  1. range(values: number[]): [number, number] returns [smallest, largest].
  2. zipPeople(names: string[], ages: number[]): [string, number][] pairs each name with the age at the same position.
main.ts
function range(values) {
}

function zipPeople(names, ages) {
}

const [low, high] = range([12, 3, 45, 9]);
console.log(low, high);

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…