TypeScript return immutable/const/readonly Array

XCS picture XCS · Apr 24, 2018 · Viewed 10.4k times · Source

I want to have a function which returns an Array, but I want the returned Array to be readonly, so I should get a warning/error when I try to change its contents.

function getList(): readonly number[] {
   return [1,2,3];
}


const list = getList();
list[2] = 5; // This should result in a compile error, the returned list should never be changed

Can this be achieved in TypeScript?

Answer

Matthew Layton picture Matthew Layton · Apr 24, 2018

This seems to work...

function getList(): ReadonlyArray<number> {
    return [1, 2, 3];
}

const list = getList();

list[0] = 3; // Index signature in type 'ReadonlyArray<number>' only permits reading.

Try it in the Playground

ReadonlyArray<T> is implemented like this:

interface ReadonlyArray<T> {
    readonly [n: number]: T;
    // Rest of the interface removed for brevity.
}