codez.guru

Typing Arrays

You can type arrays in two ways:

let numbers: number[] = [1, 2, 3];
let fruits: Array<string> = ["apple", "banana"];

Both are valid. Choose whichever is more readable in your context.


Readonly Arrays

To prevent mutation of an array:

const values: readonly number[] = [1, 2, 3];

Now methods like .push() or .splice() will trigger type errors.

values.push(4); // ❌ Error

You can also use:

const colors: ReadonlyArray<string> = ["red", "blue"];

Tuples in TypeScript

Tuples are fixed-length arrays with fixed types:

let person: [string, number] = ["Alice", 30];

Each index has a known type. Tuples are useful when:

  • The length is known
  • The order matters
  • Each element has a distinct meaning

Labeled Tuples

You can label tuple elements for better clarity (editor-only feature):

type Point = [x: number, y: number];

const p: Point = [10, 20];

> It doesn’t affect runtime, but improves readability and tooling.


When to Use Tuples vs Arrays

Use Case Recommendation
Homogeneous list Use type[] or Array<type>
Fixed-length record Use tuple
Mixed types Use tuple
Immutable list Add readonly

Summary

  • Arrays hold values of the same type; tuples hold fixed, typed positions
  • Use readonly or ReadonlyArray<t> to enforce immutability
  • Tuples are ideal when data has a known structure with position-based meaning

Coming up: union types, intersection types, and how to combine types powerfully in TypeScript.