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 think the const obj creates confusion in the example @impinball. Instead, I imagine noone would disagree that this must hold true:
class Foo {
get foo() { return 1; }
}
var obj = new Foo();
obj.foo = 2; // Error
Read-only properties have been a matter of fact in javascript since the beginning of time, and it's unambiguous that type system support for read-only properties will be immensely helpful. Any other discussions about const objects and immutable collections IMHO are not relevant to this discussion.
Once we have read-only properties we could start discussing seriously stuff like modelling javascript "frozenness" and "sealedness" formally, but all our arguing about everyone's expectations of immutability and purity here are only detracting from the discussion. I seriously suggest we focus on getting type system support for read-only properties and think immutability next thing.
Okay... I'll admit the similarity with const would be a little bit
hackish. But last time I checked, you can't assign to either one, const
or getter without setter. You can get the value of either one, but they
can't be assigned to. Because they behave identically on the left hand side
(excluding getter side effects), that's why I suggested it.
As for const obj vs var obj, I typed const out of habit. Any of the
three declarations would suffice.
On Fri, Sep 18, 2015, 05:26 Hristo Dachev [email protected] wrote:
I think the const obj creates confusion in the example @impinball https://github.com/impinball. Instead, I imagine noone would disagree that this must hold true:
class Foo { get foo() { return 1; } } var obj = new Foo(); obj.foo = 2; // Error
Read-only properties have been a matter of fact in javascript since the beginning of time, and it's unambiguous that type system support for read-only properties will be immensely helpful. Any other discussions about const objects and immutable collections IMHO are not relevant to this discussion.
Once we have read-only properties we could start discussing seriously stuff like modelling javascript "frozenness" and "sealedness" formally, but all our arguing about everyone's expectations of immutability and purity here are only detracting from the discussion. I seriously suggest we focus on getting type system support for read-only properties and think immutability next thing.
— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/12#issuecomment-141396042 .
This is now Typescript 1.6 available and still no support for this feature. You even implemented a support for third party library like the React in this version and still no long awaited and long discussed support for the compiler to check that the property has no setter. I had a bug in my project because the compiler did not give any hint while i assigned values to readonly properties.
Could you please make this feature in the compiler because it is needed for large projects like mine https://github.com/BBGONE/jRIAppTS
I suggest a quick and effective solution. As a compromise you can allow implicit casting immutable => mutable is OK. Just don't allow assignment to a readonly property when the variable has type of the interface with that property marked readonly. It is needed because developers who create frameworks define interfaces in it which can be consumed by clients and the clients should be aware what property is readonly and which is not. It is up to them to follow the contract what the developers provided. For example: an Entity can have calculated property and the clients should be aware that the property is readonly. It will cover 99% of usecases. Very litle developers care about the issues that a function can accept an argument and modify it internally. Most of the problem is when you work with properly typed variables (with readonly properties) and there's an assignment to it in the code.
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; // immutable => mutable ALLOW IT! pt2.x = 6; // ALLOW IT because it is now mutable pt= pt2 //IT is again immutable pt.x = 7; // Error, 'pt.x' is not a valid target of assignment
P.S. - reclassify this issue as a bug, because technically it is a bug : the compiler should check that a property can not be wriitten because a developer explicitly did not provide a setter.
@BBGONE
Only the part regarding getters without setters could remotely be considered a bug. The rest cannot, such as the readonly modifier for other types. The feature didn't exist before, and it's not directly mis-typing the language. And in case you're curious, even the mis-typing of this was considered a suggestion, not a bug. That problem came down to JavaScript being call-by-delegation in its object model, like Lua or Python, vs TypeScript typing it like a language with statically known methods like Java or C# (which isn't accurate at all).
@impinball "even the mis-typing of this was considered a suggestion, not a bug." It is considered a suggestion because it has an easy workaround and i use it often: instead of untyped 'this' use a typed 'self'
function f() { var self: SomeType = this; self.x = 3; }
But the issue with ReadOnly properties have no workaround. And my proposal can easily be implemented transparently to the existing codebase. Developers can then use interfaces with the new features, and their code will be protected from that bug if they use interfaces and typing consistently. Third party libs can be left as is.
@BBGONE
The thing with this is that even Function.prototype.call is improperly typed. The standard library doesn't correctly take this into account.
As for readonly properties, it's still a feature. It's not a feature that was improperly/incorrectly implemented. Those constitute actual bugs.
I really don't understand why this conversation is still going in circles. The spirit of the issue as a requested feature has nothing whatsoever to do with deep immutability. This is specifically nothing more than having a compiler error when we know at build time that, given the implicit or explicit interface of an object, an assignment is absolutely guaranteed to always cause a runtime error.
I say this with full appreciation for the fact that syntax changes merit very serious scrutiny. I just propose that other immutability features should be forked to a different issue and considered OT here.
@joelday I agree with the entirety of your statement.
Back to the initial discussion, I do believe that there needs to be a way of marking whether something can be read or written. This would be an awesome thing to be able to have:
interface LodashArray {
readonly length: number;
}
There's no way I can possibly modify the length without something going wrong. Also, assigning to getters without setters should also fail in this case:
class Foo {
get foo() { return 2 }
}
new Foo().foo = 3 // error!
let foo = new Foo().foo // okay
Also, there should be a way to properly type setters without getters. I know it's not very common and not very elegant, but JS and TS both allow it, so it should be checked, anyways.
class Foo {
set foo(value) { /* ... */ }
}
let foo = new Foo().foo // error!
new Foo().foo = 2 // okay
@jbondc You mean s/writable/readable/g and s/mutable/writable/g? ;)
Also, what about get T and set T? There is no existing ambiguity AFAIK, since there's just whitespace between the two tokens.
Ok. It really confused me. To be honest, I don't like that naming for that very reason: it's non-obvious.
On Mon, Oct 19, 2015, 08:36 Jon [email protected] wrote:
@impinball https://github.com/impinball Yes well:
- !writable reads as Not Writable (readable).
- !mutable reads as Not Mutable (constant, immutable, ..?)
I explain it more here about attaching constraints to a type: #3076 (comment) https://github.com/Microsoft/TypeScript/issues/3076#issuecomment-100675816
— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/12#issuecomment-149201689 .
I would read number!writable as "number that is writable", and number!writable!enumerable as "number that is writable and enumerable". Is that what you meant?
Couple of thoughts:
- Wouldn't
writablebe better defined by simply the existence of the set property function? I realize that these are defined separately in JavaScript - but that makes more logical sense to me. - For other property metadata (like
configurableandenumerable), rather than creating a new syntax couldn't decorators be repurposed for this? I mean using some well recognized decorators defined internally to the compiler?
Alternative I guess could be:
declare class Foo {
someValue: number;
foo: number{writable: false, enumerable: false}
}
@joewood Properties are writable in JS so not sure what you meant by the set property:
class Foo {
someValue = 1
set foo() { this.someValue++ }
}
The emit in a declaration file would be:
declare class Foo {
someValue: number;
foo: number;
}
With decorators, look at the generated code: http://www.typescriptlang.org/Playground#src=%40A%0Aclass%20Clazz%20{%0A%20%20%20%20%40B%0A%20%20%20%20prop%20%3D%201%3B%0A%0A%20%20%20%20%40C%0A%20%20%20%20method%28%29%20{}%0A%0A%20%20%20%20%40D%0A%20%20%20%20get%20prop%28%29%20{return%201%3B}%0A%0A%20%20%20%20%40E%0A%20%20%20%20method2%28%29%20{}%0A%0A%20%20%20%20%40F%0A%20%20%20%20prop2%20%3D%201%3B%0A}
Not something I'm particularly excited about. They are a runtime thing and can't be applied to types/interfaces etc...
e.g.
function enumerable(proto, name) {
Object.defineProperty(proto, name, { value: undefined, enumerable: true });
}
class Foo {
@enumerable
a: number;
}
The emit in a declaration file is:
declare function enumerable(proto: any, name: any): void;
declare class Foo {
a: number;
}
So you lose the info.
@jbondc I mean if the emit included a declaration for the getter/setter. The compiler would then error if you were trying to use the property as an lvalue in an expression. This seems more natural to me, unless I'm missing something.
For decorators - I'm talking about reusing the syntax as a way of adding metadata, not as a runtime evaluation or generating any code. So this would just be used for metadata exposed to the compiler.
So you mean:
class Foo {
someValue = 1
get foo() { return this.someValue }
}
Declaration is:
declare class Foo {
someValue: number;
get foo: number;
}
Guess that can work too, syntax is more a game of perspective.
Right, seems to be more inline with the goal of declaration files being the header files of JavaScript.
And this is why I suggested get and set modifiers (I don't care if it's
prefixing the type or value name - it reads the same). I think it would
make perfect sense. The intent is very clear in that you can get and/or
set the property.
// Prefixing the name
declare class Foo {
someValue: number;
get foo: number;
}
// Prefixing the type
declare class Foo {
someValue: number;
foo: get number;
}
I'm indifferent to which is used, although I suspect most here would prefer the former.
On Mon, Oct 19, 2015 at 11:46 AM, Joe Wood [email protected] wrote:
Right, seems to be more inline with the goal of declaration files being the header files of JavaScript.
— Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/12#issuecomment-149254282 .
Isiah Meadows
Gotcha makes sense, like it.
@impinball Thanks! I think the issue with using "readonly" as a keyword in an interface is that it can be interpreted as declaring that the property cannot be writable on an object that implements that interface. Also, I think it would get confusing (or plain not work in some situations) when extending interfaces, and class declarations of get/set properties is also fundamentally additive rather than negative, so I think it would make sense for declaring it on interfaces to work the same way and use the same keywords.