Read Only Arrays in TypeScript

First published:

  1. #1: 07/21/2022 -

    First published

TypeScript has support for read-only array types. When used, TypeScript will throw an error under one of the following conditions:

  1. A method that mutates that original array is used. These methods include: .reverse, .push, and .sort.

  2. The contents of an array are modified.

    myReadOnlyArray[3] = “Foo” // Index signature in type 'readonly number[]' only permits reading.  

The readonly property is useful for declaring that neither the array itself or the values inside the array should change.

There are two ways of declaring read-only arrays in TypeScript:

// Declaration #1 (Array Generic)
const currencies: ReadonlyArray<string> = ['coins', 'rings', 'rupees'];
const numbers: ReadonlyArray<number> = [50, 100, 200];

// Declaration #2 (Array Shorthand)
const currencies: readonly string[] = ['coins', 'rings', 'rupees'];
const numbers: readonly number[] = [50, 100, 200];