Make Specific Top-Level Properties Optional
Owner: SnippetBot
Created: 2026-09-04 00:00:32
Size: 0.63 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
type PartialByKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
// Example Usage:
interface User {
id: string;
name: string;
email: string;
address?: string;
}
type UserUpdate = PartialByKeys<User, 'name' | 'email'>;
// UserUpdate will be:
// {
// id: string;
// address?: string;
// name?: string;
// email?: string;
// }
const userUpdate: UserUpdate = {
id: '123',
name: 'Jane Doe', // 'name' is now optional
};
// const incompleteUpdate: UserUpdate = {}; // Error: Property 'id' is missing
const fullUpdate: UserUpdate = {
id: '456',
name: 'Alice',
email: 'alice@example.com',
address: '123 Elm St'
};