AI Hints
Home›TypeScript Tutorial›Precise Types
TypeScript · Lesson 90 of 120

Readonly Arrays

Immutability.

⏱ 2 min read▶ Video at 1:10:17🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Functions that change an array they were given cause surprising bugs. A readonly array type removes push, pop, sort, and every other changing method.

Readonly Arrays
From the video: Readonly Arrays
  • Surprising changes
  • readonly arrays
  • No changing methods

No changes allowed

Top prices takes a readonly array. Sorting it in place is rejected, because sort changes the array. Run it.

app.tstypescript
function topPrices(prices: readonly number[]) {
  return prices.sort((a: number, b: number) => b - a).slice(0, 2);
}
Output
app.ts line 2: Property 'sort' does not exist on type 'readonly number[]'.

Copy, then change

We copy the array first, with the spread operator, then sort the copy. The original stays untouched. Run it.

app.tstypescript
function topPrices(prices: readonly number[]): number[] {
  return [...prices].sort((a, b) => b - a).slice(0, 2);
}

const prices = [450, 2199, 849.5];
console.log(topPrices(prices), "| original:", prices);
Output
[ 2199, 849.5 ] | original: [ 450, 2199, 849.5 ]

Summary

Readonly arrays block changing methods, so functions can't surprise their callers. Next, result types.

Key takeaways
  • readonly number[]
  • [...copy]
  • No surprises
Next up: Result Types — errors as values