Search code examples
typescriptimmutability

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?


Solution

  • 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.