CodePark/ questions / Access modifiers, readonly & statics
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Access modifiers, readonly & statics

Which line gives a TypeScript compile error?

class Cart {
  readonly items: string[] = [];
  add(item: string): void {
    this.items.push(item);   // Line A
  }
  reset(): void {
    this.items = [];         // Line B
  }
}
Only Line B

Only Line B fails. readonly stops you from assigning the property again. It does not freeze the value inside. So push on the array is allowed. It is also only a compile-time check: the JavaScript output has no readonly.

"Both lines" is tempting if you think
readonly means "immutable". To block push too, type the field as readonly string[] (or ReadonlyArray<string>).