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

Quick reminder that I prototyped what we're talking about a while ago: https://github.com/joelday/TypeScript/blob/getSetKeywordAssignment/tests/cases/compiler/assignmentToReadOnlyMembers.ts

:)

joelday avatar Oct 20 '15 22:10 joelday

Any progress?

Artazor avatar Dec 10 '15 15:12 Artazor

+1 for final modifier.

falsandtru avatar Dec 14 '15 14:12 falsandtru

Perhaps we can explore and borrow the idea of case classes from Scala i.e.

immutable class Point {
    public x: number;
    public y: number;
}

where x and y are automatically readonly, all immutable classes are provided a copy() or clone() methods for deep and shallow copying

if a particular property needs to be mutable for any reason, simply denote it with var i.e. public var lastModified: Date

so that's +1 for immutable class for me

erfangc avatar Dec 23 '15 13:12 erfangc

This discussion not about constants in classes, but some issues marked as duplicate of this, and I wont to show my vision about this (it also gives an option for this https://github.com/Microsoft/TypeScript/issues/3743 ). We can do something like this:

class MyClass
{
    static const MY_STATIC_CONST: string = 'my staic const';
    const MY_CONST: string = 'my const';
}

And generated JS:

Object.defineProperty(
    MyClass,
    'MY_STATIC_CONST',
    {
        value: 'my staic const',
        enumerable: true
    }
);
Object.defineProperty(
    MyClass.prototype,
    'MY_CONST',
    {
        value: 'my const',
        enumerable: true
    }
);

It looks simple and useful for me.

Avol-V avatar Dec 23 '15 19:12 Avol-V

Will we see a solution of this implemented in typescript compiler? P.S. I need a solution for the bug when you can assign a value to a property without setter and proper expression of this in the interfaces.

talk, talk , talk ....

ghost avatar Dec 24 '15 07:12 ghost

TypeScript already generates defineProperty for ES5 getters/setters. And, as I have shown, in this case we can declare properties for prototype, that is also important.

Avol-V avatar Dec 24 '15 13:12 Avol-V

I'm going to take a look at implementing something here. My current thoughts are:

  • Introduce a readonly modifier that can be applied to property and method declarations in interfaces and classes, and infer a read-only property when a class includes only a get accessor declaration for a particular property.
  • Allow the readonly modifier to also be applied to interface and class declarations, making all members introduced in that interface or class declaration read-only.
  • Disallow assignments to read-only properties, except for property initializers in classes and property assignments in constructors.
  • In subtyping and assignment compatibility checks, allow a read-write property to be treated as a read-only property, but not vice versa.

This effectively amounts to "shallow" immutability. With that in place, deeply immutable object types can be created by manually ensuring that all properties are read-only properties of primitive types (string, number, or boolean) or object types that are themselves deeply immutable (transitively).

I think this would cover the type checking side of things. I'm not sure we really want this to affect code generation (e.g. by using Object.defineProperty) since there is overhead associated with that.

ahejlsberg avatar Jan 11 '16 18:01 ahejlsberg

This effectively amounts to "shallow" immutability.

Isn't that shallow immutability logic the same logic as const, therefore relatively straight forward to guard against?

kitsonk avatar Jan 11 '16 19:01 kitsonk

Could readonly also be applied to parameter types as a type modifier providing a read-only reference to an existing object? Only getters and readonly members would then be available to that function. e.g.:

function doThis( someObject: readonly Foo ) {
    someObject.prop = 123; // error
    var v = someObject.prop; // ok
} 

In a similar way to C++ const. Without a type-modifier I suspect we'll end up writing interface definitions twice, once for immutability and again for mutability.

joewood avatar Jan 12 '16 00:01 joewood

@kitsonk The difference between const and readonly is that it isn't possible to alias a const and therefore you're guaranteed it will never be mutated. With readonly you can fairly easily create a type with all read-only properties that aliases an object with read-write properties. In that scenario it is still possible for mutations to happen, it's just that you can't cause them.

@joewood The issue with readonly as a type modifier is that it may not do what you expect. For example, a readonly string[] would still have a push method that mutates the array. All readonly would do is keep you from assigning to the properties of the array.

ahejlsberg avatar Jan 12 '16 01:01 ahejlsberg

@ahejlsberg maybe I not following, but wouldn't push be inaccessible because it wouldn't be marked as readonly because it mutates. Whereas functions like slice would have a readonly modifier, or doesn't it work like that.

joewood avatar Jan 12 '16 02:01 joewood

It's probably worth breaking down several of the concepts of readonlyness that some languages have so we can clarify which would and would not exist:

  1. Is the object I'm referencing mutable or immutable ? i.e. am I allowed to do things to this object which mutate its state, via this reference?
  2. Is this reference (primitive or otherwise) a mutable reference or an immutable reference? i.e. am I allowed to change this reference to point to a different object (or different value)?
  3. Is a given property of an object ever settable, even when the object is mutable?

Using C++ as the most direct analogy, we can understand the difference between 1 and 2 as the difference between const int* x and int* const x. Since C++ doesn't have property getters/setters, point 3 reduces to point 1 (modulo the mutable keyword).

Since C++ doesn't have the ability to set e.g. std::vector.insert on an arbitrary object reference, it doesn't have to make any subtle distinctions that a hypothetical JavaScript-based full understand of mutability would require. To clarify: there are two concepts you might want to express about Array#indexOf or Array#push -- you don't want to allow arbitrary setting of those properties, but only the latter causes mutation of the underlying object when invoked. It's worth thinking about how std::vector.size() is a method, rather than a field, in that context (you can't set the size of a mutable std::vector via that member).

What's on the table (as far as I understand) is the following:

  • You can declare that object properties are not settable. For example, setting the length of a Function does nothing and should be a compile-time error.
  • You cannot declare or determine that a method does or does not alter the state of an object. For example, calling someArray.slice() (which does not modify the object) and someArray.reverse() (which does) are indistinguishable.
  • You can declare that all fields of a class or interface are read-only, but this is just a shortcut for declaring each property of that type with the readonly modifier.
  • Existing behavior of const vs. let/var cover reference immutability for variables

Since now I've written all this and now realize that there's a much simpler explanation, consider this symmetry:

const items: string[] = []; // OK, initializer
items.push('ok'); // OK
items = []; // Nope, const reference

and

readonly class MyClass {
  items: string[]; // readonly because containing class is readonly
  constructor() {
    this.items = []; // OK, initializer
  }
}
let m1 = new MyClass();
m1.items.push('hello'); // OK
m1.items = []; // Nope, readonly property
m1 = new MyClass(); // OK, not a const reference

const m2 = new MyClass();
m2.items = []; // Still an error
m2.items.push('world'); // Still OK
m2 = new MyClass(); // Nope, const reference

RyanCavanaugh avatar Jan 12 '16 07:01 RyanCavanaugh

...and if the user wanted more run-time immutability they could:

readonly class MyClass {
  items: string[]; // readonly because containing class is readonly
  constructor() {
    this.items = []; // OK, initializer
    Object.freeze(this.items);
  }
}

const m3 = new MyClass();
m3.items.push('world'); // Throws an error in strict mode (or noop otherwise)

TypeScript hasn't "tracked" that type of immutability to date and I suggest the proposal for readonly also would just leave that behaviour to the runtime?

kitsonk avatar Jan 12 '16 07:01 kitsonk

@ahejlsberg Maybe your readonly modifier is not the same as const/final modifier in classes, that me and some other people expect. I'm looking for ability of creating constants in classes such as in other languages and as we can see in javascript standard objects: Node.ELEMENT_NODE, XMLHttpRequest.DONE and other (in js we also can have access to these constants from instances, because of prototypes, but it's not really needed). And these constants in js is read-only — I just want to have ability to declare such constants in TypeScript easely.

But, maybe, your readonly is OK, I have only one question — why you don't want to make class instance read-only properties assigned once for prototype and not for each instance?

Avol-V avatar Jan 12 '16 13:01 Avol-V

Such a long discussion and finally things become clearer!

@RyanCavanaugh All that's on the table is correct but there's a small thing I want to mention about - the difference in getter/setter accessors visibility.

I agree that an object property can have no setter:

const foo = {
    get bar() {
        return 0;
    }
}

foo.bar = 1; //error

I think this is clear. But here's a bit more complex example that describes the problem:

declare abstract class Emitter {
    new (): Emitter;
    on: (name:string, handler: (arg:any) => void) => void;
    off: (name:string, handler: (arg:any) => void) => void;
    protected emit: (name:string, arg:any) => void;
}

class Person extends Emitter {
    constructor(name:string) {
        super();
        this.name = name;
    }

    private _name:string;
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.emit('change:name', value);
            //this way is better
            this.updatedAt = new Date();
            //than this way
            this.setUpdatedAt(new Date());
        }
    }

    ////
    private _updatedAt:Date;
    get updatedAt() {
        return this._updatedAt;
    }
    private set updatedAt(value) { //Getter and setter do not agree in visibility
                //some logic and a simple readonly (our absence of a setter) is not enough
        if (this._updatedAt !== value) {
            this._updatedAt = value;
            this.emit('change:updatedAt', value);
        }
    }

    //// method implementation - but what's the point in it?
    private setUpdatedAt(value) {
        if (this._updatedAt !== value) {
            this._updatedAt = value;
            this.emit('change:updatedAt', value);
        }
    }
}

const entity = new Person('Mike');
entity.on('change:updatedAt', console.log.bind(console));
entity.name = 'Thomas';
//but manually setting updatedAt should be forbidden
entity.updatedAt = new Date(); //restricted

Here, property updatedAt actually can have a setter but it should not be accessable outside of Person. Moreover this setter contains complex logic and a simple readonly or an absence of a setter is not enough.

I agree that private setter is just a syntax sugar for private methods with additional logic (like emitting) but I think it is inconsistent when part of logic related to a field is in a property (getter) and another in a method (actual private setter).

This way getters/setter are implemented in C#, I think it would be usefull to allow different visibility at a compile time, though this contracts will be lost in runtime.

UPDATE I've found the duplication of my suggestion: #2845 but it is linked and closed

raveclassic avatar Jan 12 '16 13:01 raveclassic

@RyanCavanaugh yes, understood. My two requests are really:

Type Modifier Not having a type modifier on a reference (no. 2 above on your list) will mean that if you want to pass around an immutable reference to an object you will end up having to duplicate the interface definition with a simple readonly before the declaration. That seems a little frustrating, especially given how popular immutability is becoming on the client side. So something like this (even though it's only shallow)

interface Foo {
   x: number;
   y: Bar;
}

function doSomething( foo: readonly Foo ) { // or maybe using the const keyword
   foo.x = 10; // error
   var x = foo.x; // ok
   foo.y.bar = 10; // unfortunately ok because only shallow
}

Note, without this the developer would need to declare Foo and also a duplicate interface ImmutableFoo.

Context Type Modifier Second request is to be able to decorate a function that acts as a type modifier for this. Property getters have this set implicitly.

interface Foo {
    readonly getState() : number;
    resetState();
}

function readFoo( foo: readonly Foo ) {
    let state = foo.getState(); // OK, works as readonly context function
    resetState(); // error - mutating function
}

With a type modifier you could define a getter that returns a readonly type, so the immutability isn't just shallow. I think the interface definition would need to be extended to support that, or add some sort of immutable directive to the type definition.

joewood avatar Jan 12 '16 13:01 joewood

@Avol-V Both Node.ELEMENT_NODE, XMLHttpRequest.DONE are not constants but enums which are immutable be design and you can just export them from the module along with the class using them - this is the proper way in ES6/TS.

If you need an immutable property on the class you can define it with only a getter:

export enum NodeType {
    ELEMENT_NODE,
    SOME_OTHER_NODE_TYPE
}

export class SomeElement {
    private _type:NodeType;
    get type() {
        return this._type;
    }
}

This works right now except of the ability to write to a property without a setter which was considered a bug eariler in the conversation. No readonly/final/immutable etc.

raveclassic avatar Jan 12 '16 15:01 raveclassic

@raveclassic No, Node and XMLHttpRequest and others — is a classes, not enums. And ELEMENT_NODE and others — is constant in namespace of this class. Your example is wrong. Correct example is:

class Node
{
    …
}
namespace Node
{
    export const ELEMENT_NODE: number = 3;
}

But in this case I have troubles with inheritance.

Avol-V avatar Jan 12 '16 15:01 Avol-V

@Avol-V Yes, you are right, misunderstood. I can see now that your point is about inheriting class constants. The problem here is that this issue is bloated and should be split. We are all talking about different things.

raveclassic avatar Jan 12 '16 15:01 raveclassic