Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Mutability and inversion of Readonly<T>

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?

like image 585
Matthew Layton Avatar asked Jan 29 '26 09:01

Matthew Layton


1 Answers

Yes, you can use -readonly in type definition.

type Mutable<T> = {
  -readonly [P in keyof T]: T[P];
};

const foo: Mutable<Foo> = new Foo(123);
foo.bar = 456;

Playground

But remember it's only type definition, it doesn't change original logic.

type Mutable<T> = {
  -readonly [P in keyof T]: T[P];
};

class Foo {
    get test(): boolean {
      return true;
    }

    constructor(public readonly bar: any) { }
}

const foo: Mutable<Foo> = new Foo(123);
foo.bar = 456;
foo.test = false; // oops, it will cause an error.
like image 71
satanTime Avatar answered Jan 31 '26 02:01

satanTime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!