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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With