beginner Step 3 of 18

Arrays and Tuples

TypeScript Programming

Arrays and Tuples

Arrays and tuples are fundamental data structures in TypeScript that let you work with ordered collections of values. While JavaScript arrays are untyped and can hold any mix of values, TypeScript adds type safety so the compiler can verify that every element in a collection matches the expected type. Tuples extend this concept by allowing you to define arrays with a fixed number of elements where each position has a specific type, making them ideal for representing structured pairs or small records without defining a full interface.

Typed Arrays

TypeScript offers two equivalent syntaxes for declaring array types. The first uses square bracket notation, and the second uses the generic Array<T> form. Both produce identical compiled JavaScript.

// Square bracket syntax (preferred for simple types)
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
let flags: boolean[] = [true, false, true];

// Generic syntax (useful for complex types)
let scores: Array<number> = [95, 87, 72, 100];
let items: Array<string | number> = ["apple", 3, "banana", 7];

// The compiler catches type errors
numbers.push(6);      // OK
// numbers.push("seven"); // Error: Argument of type 'string' is not
//                        //   assignable to parameter of type 'number'

Array Methods with Type Safety

All standard JavaScript array methods work in TypeScript with full type inference. Methods like map, filter, and reduce automatically infer the types of callback parameters and return values.

const prices: number[] = [29.99, 49.99, 9.99, 79.99];

// map — TypeScript infers doubled as number[]
const doubled = prices.map(price => price * 2);

// filter — TypeScript infers affordable as number[]
const affordable = prices.filter(price => price < 50);

// reduce — accumulator type inferred from initial value
const total = prices.reduce((sum, price) => sum + price, 0);

// find — returns number | undefined (might not find anything)
const found = prices.find(price => price > 40);
if (found !== undefined) {
  console.log(`Found: $${found.toFixed(2)}`);
}

Tuples

A tuple is a fixed-length array where each element has a known type at a specific position. Tuples are useful for returning multiple values from a function or representing key-value pairs without creating a full object type.

// Basic tuple: [string, number]
let user: [string, number] = ["Alice", 30];
let name = user[0]; // type: string
let age = user[1];  // type: number
// user[2];          // Error: Tuple type has no element at index '2'

// Tuple with optional element
let record: [string, number, boolean?] = ["Bob", 25];

// Named tuple elements (TypeScript 4.0+)
type UserTuple = [name: string, age: number, active: boolean];
const admin: UserTuple = ["Charlie", 35, true];

// Tuple as function return type
function getMinMax(nums: number[]): [number, number] {
  return [Math.min(...nums), Math.max(...nums)];
}

const [min, max] = getMinMax([3, 1, 4, 1, 5, 9]);
console.log(`Min: ${min}, Max: ${max}`); // Min: 1, Max: 9

Readonly Arrays and Tuples

Use readonly to create immutable arrays and tuples that cannot be modified after creation. This is valuable for data that should not change, such as configuration values or constant lookup tables.

// Readonly array
const colors: readonly string[] = ["red", "green", "blue"];
// colors.push("yellow"); // Error: Property 'push' does not exist
//                        // on type 'readonly string[]'

// Readonly tuple
const point: readonly [number, number] = [10, 20];
// point[0] = 5; // Error: Cannot assign to '0' because it is read-only

// ReadonlyArray generic form
const ids: ReadonlyArray<number> = [1, 2, 3];

Rest Elements in Tuples

Tuples can include rest elements to represent a fixed head followed by a variable-length tail, combining the structure of tuples with the flexibility of arrays.

// First element is string, rest are numbers
type LogEntry = [string, ...number[]];
const entry: LogEntry = ["temperature", 72, 74, 71, 73];

// Spread in function parameters
function logData(label: string, ...values: number[]): void {
  console.log(`${label}: ${values.join(", ")}`);
}
logData("scores", 95, 87, 92);
Tip: Prefer tuples over objects when the data is simple and positional (like coordinates or RGB values). Use interfaces or type aliases when the data has named fields or complex structure.

Key Takeaways

  • Use number[] or Array<number> syntax to declare typed arrays.
  • TypeScript infers element types in array methods like map, filter, and reduce.
  • Tuples are fixed-length arrays with specific types at each position, declared as [string, number].
  • Use readonly arrays and tuples to prevent accidental mutation.
  • Rest elements in tuples combine fixed-position types with variable-length tails.