Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a clone function to make readonly properties writable in TypeScript?

Tags:

typescript

I have read only data in typescript and a clone function:

class Data {
    readonly foo: string;
}

const ro: Data = {
    foo: 'bar'
}
// how to declare clone so that it returns writable data?
declare function clone<T>(val: T): T;

const rw = clone(ro);
// how to make the properties of rw writable?
rw.foo = 'changed';

How to declare the clone function so that the properties of the object it returns are writable?

like image 613
Michael_Scharf Avatar asked Feb 13 '17 22:02

Michael_Scharf


1 Answers

There is an even newer way to accomplish this, but I don't think updating the answer that's already here would be the best way to document this.

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

This has the additional benefits of preserving optional modifiers and only requiring one generic parameter.

(code in playground)

like image 136
knpwrs Avatar answered Oct 09 '22 07:10

knpwrs