Search code examples
typescriptmapped-types

When mapping on a type, how to make the keys not readonly?


The question is as simple as the title suggests: how do I make keys writable (instead of readonly) when mapping from a type that is Readonly?

f.e.

type Foo = Readonly<{
  foo: number
  bar: number
}>

type Bar = /* how to copy the Foo type, but make it writable? */

Solution

  • Use -readonly to remove readonly when mapping e.g.

    export type Foo = Readonly<{
      foo: number
      bar: number
    }>;
    
    export type Writeable<T> = {
      -readonly [P in keyof T]: T[P];
    };
    
    export type Bar = Writeable<Foo>;
    let x:Bar = {
      foo: 123,
      bar: 456
    }
    x.bar = 123; // OK 
    

    🌹