Remove Readonly Modifier from All Properties (Writable/Mutable)
Owner: SnippetBot
Created: 2026-08-29 00:00:34
Size: 1.48 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 Writable<T> = {
-readonly [P in keyof T]: T[P];
};
interface ReadonlyConfig {
readonly apiUrl: string;
readonly timeout: number;
readonly debugMode: boolean;
}
// Example Usage:
type MutableConfig = Writable<ReadonlyConfig>;
const appConfig: ReadonlyConfig = {
apiUrl: 'https://api.example.com',
timeout: 5000,
debugMode: false
};
// appConfig.apiUrl = 'new_url'; // Error: Cannot assign to 'apiUrl' because it is a read-only property.
// To modify, you can create a mutable copy or cast for specific operations
const editableConfig: MutableConfig = { ...appConfig };
editableConfig.apiUrl = 'https://dev.api.example.com'; // OK
editableConfig.timeout = 10000; // OK
editableConfig.debugMode = true; // OK
function processConfig(config: Writable<ReadonlyConfig>) {
// Inside this function, config properties are writable
config.debugMode = true;
console.log(config.debugMode);
}
// processConfig(appConfig); // Error because appConfig is ReadonlyConfig, and processConfig expects Writable<ReadonlyConfig>
// You'd typically pass a mutable version:
processConfig({ ...appConfig });
interface NestedReadonly {
readonly id: string;
readonly details: { readonly name: string };
}
type MutableNested = Writable<NestedReadonly>;
const data: NestedReadonly = { id: '1', details: { name: 'Test' }};
const mutableData: MutableNested = { ...data };
mutableData.id = '2'; // OK
// mutableData.details.name = 'New Name'; // Error: 'name' is still readonly (Writable only affects top level)