Search code examples
javascripttypescriptimmutabilityreadonly

TypeScript return immutable/const/readonly Array


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?


Solution

  • 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.
    }