1

Give the class:

class Foo {
    public readonly arr: number[]
    constructor(arr: number[]) {
        this.arr = arr
    }
}

Given that arr is readonly, the following shouldn't work:

foo.arr = [1,2]

However, can I push/pop to this arr with:

const foo = new Foo([1,2,3])
foo.arr.pop()
foo.arr.push(4)
Bovard
  • 1,175
  • 1
  • 14
  • 22
  • Possible duplicate of [Can TypeScript's `readonly` fully replace Immutable.js?](https://stackoverflow.com/questions/55905801/can-typescripts-readonly-fully-replace-immutable-js) – jcalz May 19 '20 at 16:31

1 Answers1

1

Yes, you can add/remove elements to a readonly array with no issue. The readonly keyword will check for reassignment and flag a compiler error if it's detected.

Bovard
  • 1,175
  • 1
  • 14
  • 22