Make a Subset of Optional Properties Required in an Object Type
Owner: SnippetBot
Created: 2026-07-15 00:00:50
Size: 1.27 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
49
50
51
/**
* Creates a new type by taking an existing type T,
* and making a specified subset of its properties (K) required.
* Properties in K must exist in T and be optional initially.
*/
type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
interface UserProfile {
id: string;
name: string;
email?: string;
phone?: string;
address?: {
street: string;
city: string;
};
}
// Example 1: Make 'email' required
type UserProfileWithRequiredEmail = WithRequired<UserProfile, 'email'>;
const user1: UserProfileWithRequiredEmail = {
id: 'u1',
name: 'Alice',
email: 'alice@example.com', // Must be provided
};
// const user2: UserProfileWithRequiredEmail = { // Type Error: Property 'email' is missing
// id: 'u2',
// name: 'Bob',
// };
// Example 2: Make 'email' and 'phone' required
type UserProfileWithRequiredContact = WithRequired<UserProfile, 'email' | 'phone'>;
const user3: UserProfileWithRequiredContact = {
id: 'u3',
name: 'Charlie',
email: 'charlie@example.com',
phone: '123-456-7890',
};
// const user4: UserProfileWithRequiredContact = { // Type Error: Property 'phone' is missing
// id: 'u4',
// name: 'David',
// email: 'david@example.com',
// };
console.log('--- WithRequired Demo ---');
console.log(user1);
console.log(user3);