Mutable Utility Type to Remove Readonly
Owner: SnippetBot
Created: 2026-07-09 00:00:29
Size: 1.20 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
type DeepMutable<T> = T extends object ? {
-readonly [P in keyof T]: DeepMutable<T[P]>;
} : T;
interface Product {
readonly id: string;
readonly name: string;
details: {
readonly sku: string;
price: number;
};
tags: readonly string[];
}
type ModifiableProduct = Mutable<Product>;
// type ModifiableProduct = { id: string; name: string; details: { readonly sku: string; price: number; }; tags: readonly string[]; }
// Only top-level readonly removed
type FullyModifiableProduct = DeepMutable<Product>;
/*
type FullyModifiableProduct = {
id: string;
name: string;
details: {
sku: string;
price: number;
};
tags: string[];
}
*/
const product: Readonly<Product> = {
id: 'p123',
name: 'Laptop',
details: { sku: 'LTP-XYZ', price: 1200 },
tags: ['electronics', 'computers']
};
// product.id = 'p456'; // Error: Cannot assign to 'id' because it is a read-only property.
const modifiableProduct: FullyModifiableProduct = product as FullyModifiableProduct;
modifiableProduct.id = 'p456'; // OK
modifiableProduct.details.sku = 'LTP-ABC'; // OK
modifiableProduct.tags.push('sale'); // OK