Skip to content

Suggestion: Use the keyword "readonly" as an accessor for classes #10064

Closed
@paleo

Description

@paleo

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions