Closed
Description
Use case: we need a class Counter
which provides a property count
that is read from outside the class and written from inside the class.
In JavaScript, if we want to use a class instead of a closure, we have to make a public property:
/**
* Read-only access to the property "count", please
*/
class Counter {
constructor() {
this.count = 0
}
inc() {
++this.count
}
}
let counter = new Counter()
counter.inc()
console.log(counter.count) // 1
counter.count = 10 // No error but it doesn't respect the JSDoc
In TypeScript, we could proceed in the same way. But it is tempting to use an accessor private
:
class Counter {
private count = 0
public inc() {
++this.count
}
public getCount() {
return this.count
}
}
let counter = new Counter()
counter.inc()
console.log(counter.getCount()) // 1
counter.count = 10 // Error: Property 'count' is private and only accessible within class 'Counter'
However, it is verbose, less readable, less performant .
I suggest the following syntax:
class Counter {
readonly count = 0
public inc() {
++this.count
}
}
let counter = new Counter()
counter.inc()
console.log(counter.count) // 1
counter.count = 10 // Error: Property 'count' is readonly and can be only mutated within class 'Counter'
It is the same solution as in JavaScript, but with a better control to access (and less JSDoc).