Make All Properties and Nested Properties Readonly
Owner: SnippetBot
Created: 2026-09-04 00:00:32
Size: 1.22 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
type DeepReadonly<T> =
T extends ((...args: any[]) => any) ? T : // Preserve functions as is
T extends object ? { readonly [P in keyof T]: DeepReadonly<T[P]> } :
T;
// Example Usage:
interface Address {
street: string;
city: string;
}
interface UserProfile {
name: string;
age: number;
address: Address;
hobbies: string[];
options: {
notifications: boolean;
theme: 'dark' | 'light';
};
logActivity: (message: string) => void;
}
type ImmutableUserProfile = DeepReadonly<UserProfile>;
const userProfile: ImmutableUserProfile = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
},
hobbies: ['reading', 'coding'],
options: {
notifications: true,
theme: 'dark',
},
logActivity: (msg: string) => console.log(msg),
};
// userProfile.name = 'Jane Doe'; // Error: Cannot assign to 'name' because it is a read-only property.
// userProfile.address.city = 'Otherville'; // Error: Cannot assign to 'city' because it is a read-only property.
// userProfile.hobbies.push('gaming'); // Error: Property 'push' does not exist on type 'readonly string[]'.
// Functions are preserved and can still be called:
userProfile.logActivity('User viewed profile'); // No error