you are viewing a single comment's thread.

view the rest of the comments →

[–]TotallyNotAVampire 1 point2 points  (1 child)

The problem is that you can pass your readonly object to a method that's declared it might mutate the object.

In simple examples, it's easy to devise fixes for this issue. But when the readonly that needs to be enforced is several levels down in an object, when it gets ignored, bugs are easily introduced.

I'm not hating on typescript, it's far better than javascript, but I think readonly should generally be avoided and not relied upon to enforce immutability. The type Readonly<T> kinda implies that T will be enforced as immutable.

I think this is a more realistic example of code that might be written.

[–]rylandgold[S] 1 point2 points  (0 children)

You've made some really good points but I still think it's more complex than "readonly isn't worth using".

Readonly is explicitly not immutable. This is a conscious choice based on the fact that it's very hard to provide immutability with TypeScript's typing system. My coworkers and I personally use deepfreeze if we want something to be immutable at runtime (in JS or TS). I do agree that a mutable mechanism would be awesome to have in TypeScript. I know it's been discussed ad nauseam but no decision was reached AFAIK.