TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: read-only modifier

Open RyanCavanaugh opened this issue 12 years ago • 132 comments

Some properties in JavaScript are actually read-only, i.e. writes to them either fail silently or cause an exception. These should be modelable in TypeScript.

Previous attempts to design this have run into problems. A brief exploration:

interface Point {
    x: number;
    y: number;
}
interface ImmutablePoint {
    readonly x: number;
    readonly y: number;
}
var pt: ImmutablePoint = { x: 4, y: 5 }; // OK, can convert mutable to non-mutable
pt.x = 5; // Error, 'pt.x' is not a valid target of assignment

var pt2: Point = pt; // Error, cannot convert readonly 'x' to mutable 'x'

// Possibly bad behavior
var pt3: Point = { x: 1, y: 1 };
var pt4: ImmutablePoint = pt3; // OK
pt3.x = 5; // pt4.x is also changed?

// Really bad behavior
/** This function was written in TypeScript 1.0 **/
function magnitudeSquared(v: { x: number; y: number }) {
   return v.x * v.x + v.y * v.y;
}
// Now try to use it with ImmutablePoint
console.log(magnitudeSquared(pt)); // Error, cannot use readonly object in non-readonly call

Possible solutions?

  • Allow bivariance of mutability: this is very unsound
  • Something else clever? C++ did not do well with const contamination

RyanCavanaugh avatar Jul 15 '14 17:07 RyanCavanaugh

It is debatable and as I said I didn't find what is considered to be a good practice. The main concern is that readonly becomes 'read-write' in the output JS and it can be changed by some bad code. @joelday Suggests to use get-only properties in the class though. @mhegazy Yes, but be more specific , constructor only set.

NN--- avatar May 20 '17 18:05 NN---

Terse get syntax like C# was discussed in #10911.

Since properties (at the moment) aren't ES spec, it could be argued though that the readonly modified in a class could make a non-writable value descriptor. If someone wanted to truly shadow the value, a getter only would be the other way. So this:

class A {
  readonly a = 'foo';
  get b() {
    return 'bar';
  }
}

Would de-sugar to:

var A = (function () {
    function A() {
    }
    Object.defineProperty(A.prototype, "a", {
        value: 'foo',
        writable: false,
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(A.prototype, "b", {
        get: function () {
            return 'bar';
        },
        enumerable: true,
        configurable: true
    });
    return A;
}());

kitsonk avatar May 20 '17 18:05 kitsonk

Why is readonly diffrent from private? Privacy is not maintained in the generated js either.

mhegazy avatar May 20 '17 18:05 mhegazy

@mhegazy You are correct. I mistakenly thought that private members are implemented in some different way. Then it makes sense for same way readonly implementation.

I guess it is offtopic now. It needs some other syntax for truly readonly properties to be implemented by defineProperty and privates via symbol or some other nice hack. Thanks.

NN--- avatar May 20 '17 19:05 NN---

The usage of readonly is not completely clear for me. I wrote a question on Stackoverflow.

This following code compiles, but is it semantically correct?

interface Counter {
  readonly name: string
  readonly value: number
  inc(): number
}

function counterFactory(name: string): Counter {
  let value = 0
  return {
    get name() {
      return name
    },
    get value() {
      return value
    },
    inc() {
      return ++value
    }
  }
}

The member value is declared as readonly but its value is changing.

I would like to know if this use of readonly on the member value is a good way to proceed. The syntax is OK. But is this example semantically correct in TypeScript? Is that what the modifier readonly is for?

paleo avatar Sep 25 '17 17:09 paleo

@paleo readonly is similar to const, it doesn't define deep immutability, just some way to make less mistakes.

const x = {a:1};
x = {a:2}; // Error , cannot change x
x.a = 2; // Ok, const is not deep
let x: {readonly a:number;} = {a:1};
x = {a:2}; // x is mutable do whatever you want
x.a = 2; // Error, 'a' is readonly and doesn't allow reassignment.

For true immutability, you need to write code which makes types immutable.

NN--- avatar Sep 25 '17 17:09 NN---

@paleo readonly doesn't guarantee that a value won't change in time, it just doesn't let you write to it. That's why the word is readonly, not constant.

raveclassic avatar Sep 26 '17 06:09 raveclassic

it just doesn't let you write to it

that's not true either: https://github.com/Microsoft/TypeScript/issues/13002

zpdDG4gta8XKpMCd avatar Sep 26 '17 06:09 zpdDG4gta8XKpMCd

@aleksey-bykov Previous issue title was a bit closer then...

raveclassic avatar Sep 26 '17 06:09 raveclassic

I quote @ahejlsberg from his PR:

A good way to think of it is:

  • readonly = cannot be modified by me
  • const = cannot be modified, period

In my question on StackOverflow, I wrote two use cases using readonly. The first case matches well to "cannot be modified by me". But the second case, that I have reported above, would rather be a "cannot be modified by you".

Is that what the modifier readonly is for? Is it valid from a semantic point of view?

paleo avatar Sep 26 '17 10:09 paleo

Is that what the modifier readonly is for? Is it valid from a semantic point of view?

Like a lot of the TypeScript typing system, it is not enforceable at run-time, it is a type contract. const is a ECMAScript run-time concept which TypeScript can fully model the run-time behaviour. readonly correctly aligns to run-time behaviour when the property in question has a getter only or is a value property that is not writable. At other times, it is a design time only construct to improve type safety (just as string or number are design time only constructs).

kitsonk avatar Sep 26 '17 10:09 kitsonk

readonly correctly aligns to run-time behaviour when the property in question has a getter only or is a value property that is not writable.

Thank you, it's clearer.

I realize that I already had the answer in 2016, from @RyanCavanaugh . At that time the ES5 getter solution was not available to me because my code had to remain ES3 compatible, so I left angry and didn't take the time to understand the information. He said:

You can already have a getter-only wrapper around a private variable, which achieves the same semantics at the cost of slightly increased class size.

This is the final answer: yes, the readonly modifier can be used with an ES5 getter to achieve this semantics.

paleo avatar Sep 27 '17 08:09 paleo