Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
paleo opened this issue Aug 1, 2016 · 1 comment
Closed

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

paleo opened this issue Aug 1, 2016 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@paleo
Copy link

paleo commented Aug 1, 2016

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

@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Aug 1, 2016

readonly has already been implemented for class properties, though it has different semantics from what you're proposin. See #12 and #6532

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 1, 2016
@mhegazy mhegazy closed this as completed Sep 20, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants