This project is read-only.

Setting a property with only a get accessor

Topics: General, Language Specification
Mar 2, 2014 at 12:34 PM
I've noticed that if I have a property with only a get accessor...
private _id: number = 1;
public get id(): number
    return this._id;
... that I can still attempt to set the property... = 123;
... and the TypeScript compiler won't complain. When this actually runs as JavaScript, the set simply fails - would still be '1' after the above line.

I imagine JavaScript will silently swallow the bad assignment, but I'd have expected TypeScript to complain about this?
Mar 3, 2014 at 5:23 PM
This is a bit of a quirk from the fact that we don't describe readonly-ness in the type system. We looked into doing this about a year ago, and once it was added, readonly-ness found its way into a lot of areas. For example, you can get a handle on a function declaration, since we don't let you write to it would this also be readonly? If so, how does this play with higher-order functions that themselves take a function? Pretty quickly that readonly aspect spread to quite a lot of our code examples.

In short, there was a lot of trickiness, and we instead opted to not introduce that much complexity into the type system, which meant that you can't describe the situation above. It's possible we may check for this in the future, or that linters will check and warn on this.