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

@Avol-V The readonly modifier would be applicable on both instance and static members. The following two constructs would effectively have the same meaning:

class Foo {
    static readonly ONE = 1;
}
class Foo {
}
namespace Foo {
    export const ONE = 1;
}

The readonly modifier would have no other effects than disallowing assignments to the property and affecting assignability of the containing type (i.e. a read-write property can become read-only, but not vice versa). There are numerous other meanings it could have (e.g. put the member on the prototype object instead of on instances, control read-only-ness of the result if the member is a method, attempt to enforce deeper immutability, etc.), but those are all orthogonal issues that aren't addressed by what I'm proposing. As the length of this discussion thread aptly demonstrates, no single modifier can do it all.

ahejlsberg avatar Jan 12 '16 17:01 ahejlsberg

@ahejlsberg @RyanCavanaugh Thanks so much for digging into this a bit!

My personal preference is shallow immutability based on the following:

For classes: Inferred by a property getter that is not accompanied by a setter. (This is a guaranteed runtime failure. If we know that, it seems aligned with the design goals of the language.)

For interfaces: either get/set keywords or a readonly/const keyword that can be negated in an extending interface by a non-readonly/const declaration of the same member.

Many of the issues that have been closed and linked to this issue are asking for more or less the equivalent pattern in C#. Also, it is my impression that deep immutability is not aligned with the ES roadmap.

joelday avatar Jan 22 '16 20:01 joelday

@joelday

Also, it is my impression that deep immutability is not aligned with the ES roadmap.

I've had the same impression for a while. And for what it's worth, I've been finding that the direction JS has been going has been making me question how functional it really is. I'm getting the feeling it's functional in the sense Common Lisp or Scheme is functional, in that it has most of the basics like lambdas, lexical closures, and TCO (last two as of ES6), but it's assumed that if you need anything truly functional like immutable structures or records, you'll use a library. And mutability is generally the default. There are no typeclasses, sum types, or pattern matching conditionals (without Sweet.js, and no, this doesn't count) in the language, and such requests for TypeScript haven't really gotten very far.

I have tried to provide a couple decent ideas within es-discuss myself, and although they seemed to be the best received out of all the proposals people tried, mine still had implementors concerned of performance for one of them and the other would be very complex to implement, since JavaScript is mutable by default, and engines are optimized for that (it takes many new heuristics to make it fast again - see Erlang for a functional, dynamic language, and even that took a lot of work).

dead-claudia avatar Jan 22 '16 22:01 dead-claudia

@raveclassic

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

Edit: this does work now.

I would prefer property syntax similar to c#.

public foo : string { get; } meaning that it is readonly.

raysuelzer avatar Jan 25 '16 03:01 raysuelzer

Support for readonly properties and index signatures (#6532) is now in master.

ahejlsberg avatar Jan 27 '16 18:01 ahejlsberg

This is awesome, thank you!

bgever avatar Jan 28 '16 05:01 bgever

Great! I'm glad to see this has finally been resolved.

drakarah avatar Jan 28 '16 08:01 drakarah

Thanks a lot for this! Awesome!

raveclassic avatar Jan 28 '16 08:01 raveclassic

Thanks! That's a tricky one to handle elegantly. Looking forward to using it.

AJamesPhillips avatar Jan 28 '16 08:01 AJamesPhillips

Thanks very much!

ghost avatar Jan 28 '16 13:01 ghost

Thanks guys! Looking forward to TypeScript 2.0!

KoenT-X avatar Jun 24 '16 14:06 KoenT-X

excellent!

ghost avatar Sep 01 '16 19:09 ghost

An important missing side note: https://github.com/Microsoft/TypeScript/issues/13003#issuecomment-267787964

readonly prevents direct mutation of the declared property through that reference. That's it.

In plain English it means that #13002 is a use case yet to be looked at

zpdDG4gta8XKpMCd avatar Dec 17 '16 21:12 zpdDG4gta8XKpMCd

I didn't find anywhere best practices for readonly instead of get-only properties. Should I change all get properties to readonly ones? The main difference that I see is that readonly property will become a regular read-write property in JS whereas get-only property is not.

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

@NN--- Generally the best practices are: private readonly members and public and protected get-only properties on classes. Use readonly for interfaces that will be implemented by classes that have get-only properties. Can add examples later. OTOH maybe StackOverflow, especially their new docs site is a better venue.

joelday avatar May 20 '17 16:05 joelday

@joelday TypeScript misses shorthand for such get-only properties. If only I could write 'public get prop: string;' instead of readonly + get.

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

A getter only property will be inferred as readonly automatically.

mhegazy avatar May 20 '17 18:05 mhegazy

@mhegazy I understand this. I meant the short syntax as in C# and other languages:

interface A {
    readonly x: number;
}

class B implements A {
    readonly _x: number;
    get x(): number {return this._x; }
}

class C implements A {
    get x(): number; // This should be equivalent to B.x implementation
}

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

And readonly x: number is not good enough?

mhegazy avatar May 20 '17 18:05 mhegazy

Or u r looking for public get private set?

mhegazy avatar May 20 '17 18:05 mhegazy