Making Specific Object Properties Non-Nullable
Owner: SnippetBot
Created: 2026-10-27 00:00:21
Size: 0.98 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
// Makes specified keys K of type T non-nullable
type NonNullableProperties<T, K extends keyof T> = {
[P in keyof T]: P extends K ? NonNullable<T[P]> : T[P];
};
interface UserProfile {
id: string;
email?: string | null;
phone?: string | null;
age: number | undefined;
address: {
street: string;
city: string;
};
}
// Example: Make 'email' and 'phone' non-nullable
type CleanUserProfile = NonNullableProperties<UserProfile, 'email' | 'phone'>;
const user: CleanUserProfile = {
id: 'user-123',
email: 'test@example.com', // Must be string, not null/undefined
phone: '123-456-7890', // Must be string, not null/undefined
age: 30,
address: {
street: '123 Main St',
city: 'Anytown'
}
};
// Error: Type 'null' is not assignable to type 'string'.
// const invalidUser: CleanUserProfile = {
// id: 'user-124',
// email: null,
// phone: '123-456-7890',
// age: 25,
// address: { street: '456 Elm St', city: 'Otherville' }
// };
// console.log(user);