Skip to main content
Module 1 · Lesson 2 of 22/22 in the course~14 min
Module lessons (2/2)

Arrays and Tuple

Explore Stage

Dynamic collections vs fixed position sequences

Distinguish when a sequence can grow (array) from when each position has a unique meaning and type (tuple).

An array represents a homogeneous list of variable length (e.g. all numerical scores). A tuple, on the other hand, is a fixed-length array in which each position carries a precise meaning and can have a different type.

Syntax of homogeneous Arrays

In TypeScript you can write number[] or Array<number>. The form T[] is the most popular in modern teams for readability, while Array<T> comes in handy with compound or nested generic types.

Example 1 — Homogeneous arrays and typed iterative methods

TS
const prices: number[] = [19.99, 45.0, 12.5];
const tags: Array<string> = ['typescript', 'strict'];

// TypeScript conosce il tipo di n in ogni passaggio della pipeline
const doubled = prices.map((n) => n * 2); // inferito number[]
const longTags = tags.filter((tag) => tag.length > 5); // inferito string[]

Example 2 — Protection against mutations with readonly

A function that receives a configuration array should not modify it in place. The readonly modifier prohibits mutant methods like .push(), .pop(), and .sort() at compile-time.

TS
function computeAverage(values: readonly number[]): number {
  if (values.length === 0) return 0;
  // values.push(99); // TS2339: Property 'push' does not exist on type 'readonly number[]'
  const total = values.reduce((acc, n) => acc + n, 0);
  return total / values.length;
}

Tuples: length and position constrained

When a structure returns a (esito, messaggio) pair or a (latitudine, longitudine, città) coordinate, a tuple prevents exchanges between columns.

Example 3 — Classic and labeled tuples

TS
type GeoPoint = [lat: number, lon: number, label: string];

const milan: GeoPoint = [45.4642, 9.19, 'Milan'];
const [lat, lon, city] = milan; // lat: number, lon: number, city: string

// readonly impedisce push su tuple fisse in API critiche
const httpOk: readonly [number, string] = [200, 'OK'];

Example 4 — Optional tuples and rest elements in tuples

TS
// Terzo campo opzionale e lunghezza minima 2
type RgbOrRgba = [red: number, green: number, blue: number, alpha?: number];

const solidRed: RgbOrRgba = [255, 0, 0];
const translucentRed: RgbOrRgba = [255, 0, 0, 0.5];

Guided practice

Exercise#ts.m1.l2.e1
Attempts: 0Loading…

Declares an array called scores that contains only numbers and is initialized with the values 90, 85, and 95. Use explicit type annotation for the array. Don't use the any type.

Loading editor…
Show hint

Use number[] to annotate an array of numbers.

Solution available after 3 attempts

Exercise#ts.m1.l2.e2
Attempts: 0Loading…

Declare a tuple called point that represents a 3D coordinate (three numbers for X, Y, Z) and is initialized with the values 10, 20, 30. Uses explicit type annotation.

Loading editor…
Show hint

Use [number, number, number] in square brackets to set exactly 3 number positions.

Solution available after 3 attempts

Exercise#ts.m1.l2.e3
Attempts: 0Loading…

Declares a tuple called locationInfo that represents a geographic coordinate with its name. Must contain: latitude (number), longitude (number) and city name (string). Initialize it with the values 41.9028, 12.4964 and 'Rome'.

Loading editor…
Show hint

Combine two numbers and a string in exact order within the tuple.

Solution available after 3 attempts

Exercise#ts.m1.l2.e4
Attempts: 0Loading…

Declares a tuple called logEntry that represents a log line. It must contain in order: a timestamp (number), a severity level (string), and an error message (string). Initialize it with the timestamp 1716300000, level 'INFO' and message 'Application started'.

Loading editor…
Show hint

Exact tuple order: [number, string, string].

Solution available after 3 attempts

Check for understanding

TypeScript Quiz#ts.m1.l2.e5
Ready

Which line generates a TypeScript compilation error on this declaration?

TS
const record: [string, number] = ["CPU", 80];
Answer options
TypeScript Quiz#ts.m1.l2.e6
Ready

Why prefer readonly number[] instead of number[] in read-only parameters?

Answer options