Menu

Arrays and Tuples

Lesson 3: Arrays and Tuples

What is the difference between arrays and tuples?

Type Length Element types Syntax Example
Array Any All the same type string[] or Array<string> ['Milk', 'Eggs']
Read-only array Any, cannot change Same type readonly string[] Categories list
Tuple Fixed Can differ by position [string, number] ['Milk', 64]
Named tuple Fixed Labelled positions [name: string, price: number] Clearer tooltips

Example

const categories: string[] = ['Fruits', 'Dairy', 'Grains'];
const ratings: number[] = [5, 4, 4, 3];

// Read-only: cannot push, pop, or assign
const paymentMethods: readonly string[] = ['UPI', 'Card', 'Cash on delivery'];
paymentMethods.push('Crypto');
// Error: Property 'push' does not exist on type 'readonly string[]'.

// Tuple: [product name, price in paise, in stock]
const item: [name: string, price: number, inStock: boolean] = ['Milk 1L', 6400, true];
const [name, price] = item;

// Tuples are common as function return values
function splitAmount(paise: number): [rupees: number, paise: number] {
  return [Math.floor(paise / 100), paise % 100];
}
const [rupees, rest] = splitAmount(6450); // 64, 50

How it works

  • string[] and Array<string> mean the same thing; most teams prefer string[].
  • For mixed arrays, use a union: (string | number)[].
  • Tuples fix both the length and the type at each position, which suits small, ordered pairs such as coordinates or [value, setValue].
  • Under noUncheckedIndexedAccess (a recommended stricter option), categories[10] has the type string | undefined, reminding you the index may not exist.

Common mistakes

Mistake Effect Fix
Using a long tuple for structured data Hard to remember what position 4 means Use an object type instead
Mutating a shared array passed to a function Unexpected changes elsewhere Accept readonly T[] in parameters
Assuming arr[i] always exists Runtime undefined Enable noUncheckedIndexedAccess and check values

Key takeaways

  • Arrays hold many values of one type; tuples hold a few values in fixed positions.
  • Use readonly arrays for data that should not change.

Try it: Write a function that returns [min, max] prices from a readonly number[], and destructure the result.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details