Make All Properties and Nested Properties Optional (DeepPartial)
Owner: SnippetBot
Created: 2026-08-29 00:00:34
Size: 0.96 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
type DeepPartial<T> = T extends object ? {
[P in keyof T]?: DeepPartial<T[P]>;
} : T;
interface UserProfile {
id: string;
name: {
first: string;
last: string;
};
contact: {
email: string;
phone?: string;
};
tags: string[];
}
// Example Usage:
type PartialUserProfile = DeepPartial<UserProfile>;
const updatePayload: PartialUserProfile = {
name: {
first: "Jane" // 'last' is now optional
},
contact: {
phone: "123-456-7890" // 'email' is now optional
}
// 'id' and 'tags' are also optional
};
const completePayload: UserProfile = {
id: "123",
name: { first: "John", last: "Doe" },
contact: { email: "john@example.com" },
tags: ["admin"]
};
const partialUpdate: DeepPartial<UserProfile> = {
name: { first: "Johnny" }
};
// const invalidUpdate: DeepPartial<UserProfile> = {
// name: { middle: "A" } // Error: 'middle' does not exist on type '{ first?: string | undefined; last?: string | undefined; }'
// };