Module lessons (2/2)
Arrays and Tuple
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
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.
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
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
// 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
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.
Show hint
Use number[] to annotate an array of numbers.
Solution available after 3 attempts
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.
Show hint
Use [number, number, number] in square brackets to set exactly 3 number positions.
Solution available after 3 attempts
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'.
Show hint
Combine two numbers and a string in exact order within the tuple.
Solution available after 3 attempts
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'.
Show hint
Exact tuple order: [number, string, string].
Solution available after 3 attempts
Check for understanding
Which line generates a TypeScript compilation error on this declaration?
const record: [string, number] = ["CPU", 80];Why prefer readonly number[] instead of number[] in read-only parameters?