Suggestion: read-only modifier
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
I guess with first class immutable data structures the type system will need some way to signify immutability . This will allow the compiler to do compile time checks.
I think that the readonly keyword might be useful for private and static functions to allow for better minification of generated files. For example, I have AMD code like the following:
export class MyClass{
public myFunction() : number {
return privateFunc(3);
}
private readonly privateFunc(toSquare: number): number{
return toSquare * toSquare;
}
}
It would be more efficient minification-wise if the code were treated as follows and then generated:
function privateFunc(toSquare: number): number {
return toSquare * toSquare;
}
export class MyClass{
public myFunction() : number {
return privateFunc(3);
}
}
In the first block, "privateFunc" cannot be minified down to "a" while the second block it can. In which case the readonly keyword would be used to let the compiler know to make sure that my private/static function calls are only to other private/static functions and not to instance variables and that nowhere in the class is there code which does this.privateFunc = newFunction
I currently write code according to the second block, but only when I the private/static function follows the constraints listed in the prior paragraph. I would much rather have the compiler take care of that refactoring for me.
Thoughts?
I've tried to summarize some of the thoughts from the above thread. I am quite new to TypeScript (and JavaScript as well) - so, apologies if some of the suggestions are infeasible for one reason or another - however, I think that, at least from the specs perspective, the below could work:
Declarations
interface Point {
x: number,
y: number
}
// declaring readonly properties is done with #
interface ImmutablePoint {
#x: number,
#y: number
}
Assignments
var p1: Point = { x: 1, y: 1 }; // p1 is fully mutable
var p2: ImmutablePoint = { x: 2, y: 2 }; // underlying object is mutable
var p3: ImmutablePoint = #{ x: 3, y: 3 }; // underling object is not mutable
To illustrate the differences between the above:
p1.x = 100; // OK
p2.x = 100; // compiler error
p3.x = 100; // compiler error
var p4: ImmutablePoint = p1; // mutable objects can be cast down into immutable objects
p4.x = 100; // compiler error
p1.x = 100; // however, underlying object remains mutable and now p4.x is = 100
var p5: ImmutablePoint = #p1; // this will clone and freeze p1
p5.x = 100; // compile error
p1.x = 200; // does not affect p5.x
var p6: Point = p2; // compiler error
var p6: Point = <Point> p2; // immutable objects can be explicitly cast into mutable objects
p6.x = 100; // OK - object underlying p2 is mutable
// but
var p7: Point = <Point> p3; // OK - no way to check that object underlying p3 is not mutable
p7.x = 100; // runtime error - object underlying p3 is not mutable
// also
var p8: Point = #{ x: 1, y: 1 }; // compiler error
Function Calls
By default, function arguments are assumed to be mutable
function foo(v: { x: number; y: number }) {
v.x = 100;
return v.x * v.y;
}
foo(p1); // OK
foo(p2); // compiler error
foo(<Point> p2); // OK
foo(p3); // compiler error
foo(<Point> p3); // runtime error
but we can also explicitly make them immutable:
function foo(v: { #x: number; #y: number }) {
v.x = 100; // compiler error
return v.x * v.y;
}
foo(p1); // OK
foo(p2); // OK
foo(p3); // OK
There's a problem with allowing mutable objects to be accepted when a function expects an immutable object. Here is a slightly convoluted but illustrative:
var p1: Point = { x: 1, y: 1 }; // p1 is fully mutable
function foo(v: {#x: number; #y: number}): (factor:number)=>number {
return (factor:number) => (v.x+v.y) * factor;
}
var bar: (f:number)=>number = foo(p1);
var v1 = bar(1); // (1+1)*1=2
p2.x = 2; // legal because p1 is immutable
var v2 = bar(1); // (2+1)*1=3
// v1 !== v2
I think this is a strange behavior. foo was written with the explicit intention of having the variable v, which backs bar (thanks to closures) be immutable.
I can see how this behavior is undesirable. I think there are 2 potentially conflicting use cases for read-only properties here.
Use case 1: underlying data for a read-only property should never change (your example above) Use case 2: underlying data for a read-only property could change, but not through the exposed interface. To illustrate
interface IPerson {
firstName: string,
lastName: string,
#fullName: string // this property is read only
}
class Person implements IPerson {
constructor (public firstName: string, public lastName: string) { }
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
var person = new Person('a', 'b'); // person.fullName is now 'a b'
person.firstName = 'c'; // OK - firstName is mutable and person.fullName is now 'c b'
person.fullName = 'x y'; // compiler error
Naturally, there are 3 options to handle this:
(1) sacrifice use case 1 in favor of use case 2 (2) sacrifice use case 2 in favor of use case 1 (3) somehow accommodate both use cases
To take a stab at the 3rd option: what if we have 2 different ways to define immutable parameters in function signature? specifically:
function foo(p: IPerson) {...}
function bar(p: #IPerson) {...}
var person = new Person('a', 'b');
foo(person); // OK - foo is able to modify mutable properties of person
bar(person); // OK - bar gets a cloned&frozen copy of person - no properties can be modified
After thinking about this some more, it seems that the distinction between "read-only interface" and "read-only data" may be 2 different issues and could/should be addressed separately.
read-only interface
This is when the data cannot be modified through the exposed interface, but may or may not be modifiable through other interfaces. To illustrate:
interface Person {
firstName: string;
lastName: string;
#fullName: string;
}
interface ImmutablePerson {
#firstName: string;
#lastName: string;
#fullName: string;
}
class Person1 implements Person {
constructor (public firstName: string, public lastName: string) { }
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
class Person2 implements Person {
constructor (public firstName: string, public lastName: string) { }
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
set fullName(value: string) {
// parse value and set this.firstName and this.lastName
}
}
// the above should result in the following behavior
var p1 = new Person1('a', 'b');
var p2 = new Person2('x', 'y');
p1.firstName = 'q'; // OK - and now p1.fullName is = 'q b'
p2.firstName = 'y'; // OK - and now p2.fullName is = 'y z'
p1.fullName = 'c d'; // compiler error
p2.fullName = 'x z'; // OK - and now p2.firstName is = 'x' and p2.lastName is = 'z'
var p3: Person = p2; // OK - implicit cast of mutable to immutable
p3.fullName = 'c d'; // compiler error - Person.fullName is read-only
p2.fullName = 'i k'; // OK - and now p3.fullName returns 'i k';
var p4: ImmutablePerson = p1; // OK - implicit cast of mutable to immutable
p4.firstName = 'n'; // compiler error - ImmutablePerson.firstName is read-only
in functions
function foo1(p: Person) { ... }
function foo2(p: ImmutablePerson) { ... }
function foo3(p: { firstName: string, lastName: string, fullName: string } ) { ... }
var p1 = new Person1('a', 'b');
var p2 = new Person2('x', 'y');
var p3: ImmutablePerson = p1;
foo1(p1); // OK
foo2(p1); // OK - implicit cast from mutable to immutable
foo3(p1); // compiler error - Person1.fullName is read-only
foo1(p2); // OK
foo2(p2); // OK - implicit cast from mutable to immutable
foo3(p2); // OK
foo1(p3); // compiler error - ImmutablePerson.firstName is read-only
foo2(p3); // OK
foo3(p3); // compiler error - ImmutablePerson.firstName is read-only
// but
foo1(<Person> p3); // OK - explicit cast from immutable to mutable
I think the above behavior could be achieved with a few relatively simple rules:
(1) If a property in an interface is declared as read-only: attempts to assign value to this property via this interface should result in compile errors (2) A read/write property can be implicitly cast into a read-only property (3) A read-only property can be explicitly cast into a read/write property
read-only data
I think this is conceptually different from the above - and it relies more on what happens at runtime - rather than at compile time. Basically, the data cannot be modified through any interface. The approach could be as follows:
interface Person {
firstName: string;
lastName: string;
#fullName: string;
}
interface ImmutablePerson {
#firstName: string;
#lastName: string;
#fullName: string;
}
class Person1 implements Person {
constructor (public firstName: string, public lastName: string) { }
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
var p1: Person = new Person1('a', 'b');
var p2: #ImmutablePerson = p1; // p1 is cloned and frozen and the resulting object is assigned to p2
Basically, putting # in front of a type indicates that an object should be clones and frozen on assignment. The above could be also done as:
var p2 = #p1; // p1 is clones and frozen, and type of p2 now is equivalent to ImmutablePerson
This could also work in function signatures
function foo(p: #{firstName: string, lastName: string, fullName: string }) {
p.firstName = 'a'; // compiler error
}
var p1: Person = new Person1('a', 'b');
foo(p1); // OK - foo now has a frozen copy of p1 and altering p1 does not have any effect on argument p inside foo
Readonly should be implemented more gradually, in parts where it's known to not cause problems such as:
function something(readonly myvalue) {
myvalue.something = 5; // Compiler error
}
It would still be useful. In my current case I would like to define it in the interface method param.
interface Some {
something(readonly myvalue);
}
To make sure the implementing classes does not modify the value when called with something.
P.S. There is something peculiar with readonly parameters, cause it's easier to think that they always are readonly and only intention to mutate parameters should be written. E.g. function something(mutable myvalue), but this would require to add readonly implicitely to all parameters and explicitely to define intent to mutate parameters.
:+1:
Can we(actually you :D) just add the getter only property in interface first? I really want it, very badly! For the compatibility issue, I agree with the idea of "use strict" thing. And maybe a writable keyword for calling legacy code from strict mode.
strict {
var pt:ImmutablePoint = { x: 100, y: 200};
legacyFunction(writable pt);
}
Bump...this would become even more useful if (and maybe when) non-numeric enums become part of TS. The typical use case for enums involve zero state, just data.
:+1:
+1
+1
I would already be very happy if a simple compiler warning could be generated when trying to assign something to a property without a setter. I was refactoring by encapsulating fields into properties with only getters and forgot to change some references. (In hindsight I should have done a refactor -> rename and add an underscore to the field before changing it to private and exposing the getter). Silently failing is pretty bad if it's easy to do unintentionally :/
I agree with @drake7707, this was my main reason to start following this thread.
:+1: for @drake7707's idea; also the reason I am following this thread.
@drake7707 Here's the test from my quick shot at implementing this feature as I see it: https://github.com/joelday/TypeScript/blob/getSetKeywordAssignment/tests/cases/compiler/assignmentToReadOnlyMembers.ts
Basically, if you put "get" before an interface member or if a class "get" accessor property doesn't have a matching "set" accessor, assignment is not allowed. It probably has some holes and I could see "readonly" being a better keyword. I would very much appreciate seeing this polished up and included in the language.
In any case, as for the long history of this issue, (it's 12 out of 692) this isn't about the deep implications of immutability language features, it's about an extremely simple guard against assignment, either deliberately or when we can trivially detect, 100% for sure that the assignment will fail at runtime.
Looks good to me, the only thing that I could think of is the following:
class A {
protected _value:string = "initial";
get value():string { return this._value; }
}
class B extends A {
set value(val:string) { this._value = val; }
}
var b = new B();
b.value = "test";
alert(b.value);
I don't even know if this should be allowed, in any case, b.value is undefined
I commented in this issue because lots of issues got closed that pointed this issue out referring to this issue as root cause.
I'd like to second what was said above, readonly is totally not about immutability - you can have a readonly property without immutability, it only means you're not allowed to write to it, not that its value can't change. It's neither about complex typesystem features - the only thing that would really matter to our team would be a readonly keyword that emits errors on obvious attempts to write to a readonly property. For us it's ok if casting or otherwise losing type information breaks these guarantees, whatever, we still have implicit anys all over the place.
@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 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 emulating 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 this, they can take the responsibility to do it through the deliberate use of this feature on everything that should be immutable rather than adding magic that complicates the language.
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.
(Edit: const implies that the value itself is never a different value or object reference, though, which is not the case here, so I don't think that is a good keyword to use here. I'm leaning towards keeping "get" because then it makes sense for adding a "set" version to an extended interface.)