Assume that I have the following mutable class:
class Foo {
constructor(public bar: any) { }
}
I can define readonly
instances of this class like so:
const foo: Readonly<Foo> = new Foo(123);
foo.bar = 456; // error, can't reassign to bar because it's readonly.
What I'd like to be able to do is the inverse of this, where the class is immutable:
class Foo {
constructor(public readonly bar: any) { }
}
And then be able to make mutable versions like so:
const foo: Mutable<Foo> = new Foo(123);
foo.bar = 456;
Is this possible?
Mutable<Foo>
(where presumablyMutable<T>
is a type likeReadonly<T>
)? – Insusceptibletype Mutable<T> = { -readonly [P in keyof T]: T[P] };
. However, it's dangerous because you can change the implementation of your class Foo later thinking that bar is readonly ==> It can break your app. – Mercorr