TypeScriptUtility types

ReadonlyArray<Type>

A read-only array: no push, sort, or assignment by index.

On this page

Example

#
TypeScript
function topScores(scores: ReadonlyArray<number>, count: number): number[] {
  return [...scores].sort((a, b) => b - a).slice(0, count)
}

const results: ReadonlyArray<number> = [72, 95, 64, 88]
console.log(topScores(results, 2))
console.log(results)
Result
[95, 88]
[72, 95, 64, 88]

Definition and usage

#

ReadonlyArray<Type> describes an array that can’t be changed. It has none of the mutating methods, such as push, pop, splice, sort, or reverse, and an assignment like scores[0] = … ends in an error. What’s left are the methods that only read or create a new array: map, filter, slice, includes, join.

A shorter, equivalent notation is readonly Type[], and that’s exactly how the compiler shows this type in messages. Pick one style for your project. ReadonlyArray tends to be more readable with complex elements, e.g. ReadonlyArray<string | number> instead of readonly (string | number)[].

A regular array can be passed wherever a read-only array is expected, but not the other way around. A parameter of type ReadonlyArray<T> is therefore a promise: the function will accept any array and won’t change anything in it. The protection only works at compile time; at runtime it’s just a regular array.

Syntax

#
Syntax
const list: ReadonlyArray<Type> = […]
const list2: readonly Type[] = […]

Type parameters

#
  • Type

    any type

    The type of the array’s elements.

More examples

#
Blocked changes
TypeScript
function resetFirst(scores: ReadonlyArray<number>) {
  scores[0] = 0
  // Error: Index signature in type 'readonly number[]' only permits reading.
  scores.sort()
  // Error: Property 'sort' does not exist on type 'readonly number[]'.
}
Passing it to a function that changes the array
TypeScript
function addBonus(scores: number[]) {
  scores.push(10)
}

addBonus(results)
// Error: Argument of type 'readonly number[]' is not assignable to parameter of type 'number[]'.
//   The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.

Good practices

#
  • Type parameters as ReadonlyArray<T> when the function doesn’t change the array. It will then also accept read-only arrays, such as constants created with as const.
  • To sort without mutating, use a copy, [...list].sort(), or the toSorted() method, which needs the ES2023 version in lib.
  • ReadonlyArray works shallowly: objects inside the array can still be modified. To lock their fields too, use ReadonlyArray<Readonly<T>>.

Related entries

#

Spotted a mistake or missing an example? Write to us.