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

@joelday I love where you're going with this.

RandScullard avatar Aug 24 '15 21:08 RandScullard

I agree that it's just a matter of only being able to read a value. Getters without setters are readonly in JavaScript, generating a runtime error on violation. Constants generate the same error. They both could be better typed with read only support.

And many JavaScript libraries use this as well. It would benefit definition writers as well.

On Mon, Aug 24, 2015, 16:57 Joel Day [email protected] wrote:

@drake7707 https://github.com/drake7707 That's a perfectly good case. I don't think my class member scan is looking at inherited tree, so I should fix that. I think it would probably be useful to add support for the "set" keyword on interfaces to support the scenario where an extending interface wants to add writability. It probably makes sense to have an error when a set-only member is being read from, but nobody really uses write-only properties as far as I've ever seen.

@hdachev https://github.com/hdachev Thanks! The problem I see with how issues have been duped and closed to this issue is that simple assignment guarding has been conflated with the entire question of what immutability features should/shouldn't exist. Maybe there's a clever approach that satisfies this scenario in a better way, but in any case, I think it's reasonable to assume that most developers want the equivalent of "string Foo { get; }" in C#, despite the possibility that people focused on language design for this project might have an aversion to emulate a C# feature just because people want it.

This appears to be aligned with ES6 "const" as I understand it, but for members rather than variables. I do want to make it clear that I don't think get-only members should const implicitly when assigned to a variable. If people want more immutability than that, they can take the responsibility to do it through the deliberate use of this feature on everything that should be immutable.

TL;DR This should work like it does in C# because it's simple and it's what people have been asking for. Also, it only took a day to prototype it.

— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/12#issuecomment-134377631 .

dead-claudia avatar Aug 24 '15 21:08 dead-claudia

@RandScullard & @impinball Glad we're on the same page. :D

joelday avatar Aug 24 '15 21:08 joelday

Providing only getter does not guarantee the immutability of the property.

class A {
    private _value: string = 'initial';
    get value(): string {
        return this._value;
    }
    doSomething(): void  {
        this._value = 'another value'; // internal reassignment cannot be prevented.
    }
}

Although this issue is mainly about externally declaring object properties as immutable, I'm concerned with the immutability of the internal state (maybe I should create another issue). I hope some keyword (such as final) could inhibit reassignment of instant variables as follows:

class A {
    private final str = 'str';
    private final num: number;
    constructor(private final bool: boolean) {
        this.num = 0;
    }

    doSomething() {
        // The below codes raise compilation errors
        this.str = '';
        this.num = 0;
        this.bool = false;
    }
}

The immutability of the internal state enables simple and side effect free programming. I suppose this is an invaluable functionality based on my experience on the other OOP languages (such as Java and Scala).

kimamula avatar Sep 08 '15 04:09 kimamula

Very common in C# too. ReSharper (and I think now VS) both recommend you turn once-set internal fields into readonly fields.

RichiCoder1 avatar Sep 08 '15 04:09 RichiCoder1

For me, as long as the immutability ensured by read-only or getter-only doesn't stop at object references like the final keyword does in Java, then it would be tremendously helpful.

dsebastien avatar Sep 08 '15 05:09 dsebastien

@dsebastien If an object publishes a method which alters its internal state, then what you mentioned does not help, I'm afraid.

someMethod(readonly myValue: string[]) {
    myValue.length = 0; // if my understanding is correct, you want invalidate this, right?
    myValue.push('str');  // even then, this can happen!
}

What really ensures object immutability is to make its internal state immutable, which is what Scala's immutable collections do, for example.

kimamula avatar Sep 08 '15 06:09 kimamula

@kimamula I see what you mean but I guess it all depends on how far the TS compiler is willing to go :)

dsebastien avatar Sep 08 '15 14:09 dsebastien

Like in C++, I think what is needed is a way to restrict the context to readonly. The compiler would then make sure that only immutable functions can be called on the context. So, something like:

someMethod(readonly myValue: string[]) readonly {
    myValue.length = 0; // error because myValue is readonly and this is a property set
    myValue.push('str'); // this would error because array.push is not marked as readonly (it mutates)
    this.xxx = 0; // this would also error because someMethod is readonly
    let x = myValue.length; // this would work - property get
    let xx = myValue.map( p => p + this.xxx); // this would work - map is a readonly function accepting a readonly lambda
}

Note that the compiler would need to promote a lambda to a readonly lambda if it contains no context mutating operations.

joewood avatar Sep 08 '15 15:09 joewood

@joewood With that particular example, I'm reminded of C#/JetBrains [Pure] attribute. Would be very interesting to only allow calling "Pure" functions or getters on a variable marked readonly.

RichiCoder1 avatar Sep 08 '15 15:09 RichiCoder1

@joewood While bad practice, nothing prevents a user to implement a property getter that has side effects. (unless ofcourse you can also annotate its signature as readonly)

drakarah avatar Sep 08 '15 15:09 drakarah

I think the compiler could warn on that. If the compiler auto promotes any function (including property getters) to read-only if they don't mutate then the compiler can warn if the readonly context modifier is applied and contradicts with what the compiler sees.

Of course, the problem with this approach will be like in C++ with const. One bad apple can spoil the whole thing.

joewood avatar Sep 08 '15 17:09 joewood

Is it possible to add a check to compiler similar to "suppressImplicitAnyIndexErrors": true" that would check assignment to "get-only" properties? I think that is a good start that will cover 95% of its use cases. Immutability could be solved as a separate task. How about "checkReadonlyProperties"? I am probably reinventing hot water, but I think this would be extremely useful for many of TS programmers.

tomitrescak avatar Sep 18 '15 00:09 tomitrescak

@tomitrescak That could just as easily be solved by marking getters as readonly.

dead-claudia avatar Sep 18 '15 03:09 dead-claudia

@impinball And how can that be done? Specifying only getter and assigning value to such getter passes compilation.

tomitrescak avatar Sep 18 '15 03:09 tomitrescak

Or at least a constant reference. Something to that effect.

dead-claudia avatar Sep 18 '15 03:09 dead-claudia

@impinball you are being very confusing. How can you mark a getter as readonly so that assiging value to it will not pass compilation?

In another words, how do you make follwing fail compilation?

class MyClass {
    private theCount: number;
    private theOther: number;

    public get count() {
        return this.theCount;
    }

    public set other(value: number) {
        this.theOther = value;
    }
}

var c = new MyClass();
c.count = 5; // should fail

var e = c.other; // should fail

tomitrescak avatar Sep 18 '15 03:09 tomitrescak

@tomitrescak I mean in the sense of it being a glorified constant.

const foo = 2;
foo = 1; // Error

class Foo {
  get foo() { return 1; }
}

const obj = new Foo();
obj.foo = 2; // Error

dead-claudia avatar Sep 18 '15 04:09 dead-claudia

Well, that's not what I was proposing :/, but thanks for your insight! Sorry for hijacking the discussion.

tomitrescak avatar Sep 18 '15 04:09 tomitrescak

Defining an object as a constant is a hack @impinball, I agree with @tomitrescak that assignments to getters should fail compilation. Same for reading a getter. Moreover, an interface should be able to enforce these constraints.

@gustavderdrache nailed that in comment: https://github.com/Microsoft/TypeScript/issues/12#issuecomment-78297192

bgever avatar Sep 18 '15 06:09 bgever